我正在上传字符串位图作为"用户个人资料图像"。使用 php 上传到服务器都很好,从服务器下载也很好。问题是当我查看位图字符串时,我看到 2 个位图之间几乎没有区别,我可以解码我下载的那个。IDK 如果我以正确的方式管理字符串。
我发送的字符串位图:1
我收到的字符串位图(评论中的图片,我不能在这里放置超过 1 个链接)[2]
从 PHP 接收我的字符串的代码:
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "");
}
line = sb.toString();
String[] kvPairs = line.split(",");
一旦我用逗号分隔行:(我收到像"name":"john","age"="5",...,"bitstringImag"="/9j/4AA.." )
我正在获取位图字符串值:
String[] bitmstrIn = kvPairs[5].split(":"); //separating the key from the value
String[] bitmstrIn2 = bitmstrIn[1].split("\}"); //erasing last key in the String
String bitStr = bitmstrIn2[0].replaceAll(""", ""); //removing the added (i dont know why) backslash.
String biStrFin = bitStr.replaceAll("\\","");//removing the added (i dont know why) backslash.
而 bitStrFin 中的结果是我粘贴到评论中的结果。
如果你知道更好的方法,请告诉我我已经为此奋斗了很长时间!谢谢大家的帮助
使用 base64 字符串。链接
就我而言,这是最好的解决方案,并且效果很好。我通过php转换了图像并将其显示在我们的应用程序中。
Java:解码
public static Bitmap getBitmapByString(String encodedString){
byte[] imageBytes = Base64.decode(encodedString, Base64.NO_WRAP);
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
}
Java:编码
public static String getStringByBitmap(Bitmap bitmap){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(bitmap.getByteCount());
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
byte[] imageBytes = outputStream.toByteArray();
try {
outputStream.close();
} catch(IOException e) {
e.printStackTrace();
}
return Base64.encodeToString(imageBytes, Base64.NO_WRAP);
}
.PHP:
$base64 = base64_encode($imagedata);
$imagedata = base64_decode($base64);
很抱歉回答很晚。这是我项目中的 Java 函数和我用来创建测试数据的 PHP 函数。