在android中使用Base64

时间:2014-01-10 19:21:06

标签: php android mysql http base64

我正在将我的图像转换为字节数组然后转换为base64字符串,它会完美地转换和解码,但是当我使用php将该字符串保存到mysql数据库并从数据库中检索它时,它不解码并说坏了base64

这是我的代码。

PHP

$sql = "insert into users(username, password, email,mob,imagetext)
                            values ('".$username."', '".$password."', '".$email."', '".$mob."', '".$imageText."') ";                            

机器人

编码

 ByteArrayOutputStream baos = new ByteArrayOutputStream();  
 Bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
 byte[] b = baos.toByteArray();
 String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);

解码

 byte[] decodedByte = Base64.decode(value, Base64.DEFAULT);                     
 b = BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);

2 个答案:

答案 0 :(得分:2)

尝试从Base64.DEFAULT更改Base64编码选项。 您应该使用Base64.URL_SAFE,它将使用在发送到您的PHP脚本时不需要进行url编码的字符。 还要考虑使用Base64.NO_WRAP,它会阻止将MIME新行添加到base 64输出中。

答案 1 :(得分:1)

基于以上答案, 编码:

 String imageEncoded = Base64.encodeToString(b,Base64.NO_WRAP | Base64.URL_SAFE);

解码:

 byte[] decodedByte = Base64.decode(value, Base64.NO_WRAP | Base64.URL_SAFE);