在我的 android 应用程序中,我让用户从他/她的手机中选择一个图像文件,将其显示在 textview 中,然后在导航到下一页之前将其保存在 json 字符串中(导航到下一页与重新加载活动相同)新数据集)。
我正在使用以下两种方法将 Drawable 转换为编码字符串并将字符串解码回 Drawable。
public String encodeImageToString(Drawable d) throws Exception{
Bitmap bm = ((BitmapDrawable) d).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] byteArrayImage = baos.toByteArray();
Toast.makeText(getBaseContext(), "Size After encoding to string:"+byteArrayImage.length, Toast.LENGTH_LONG).show();
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
bm=null;
baos.close();
baos=null;
return encodedImage;
}
public Drawable decodeStringToImage(String encodedImage){
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Drawable d = new BitmapDrawable(getResources(),decodedByte);
Toast.makeText(getBaseContext(), "Size after decoding string to image: " + decodedByte.getByteCount(), Toast.LENGTH_LONG).show();
decodedByte = null;
return d;
}
我面临的问题是每次我导航回页面时,图像质量都会下降。还有我使用 Toast 在 encodeImageToString() 中显示的字节数组大小,随着每次重新加载而不断增加。
我的操作顺序是 - 将所选文件中的图像加载到 textview 中(加载时压缩图像。我没有共享上面的代码) - 一旦用户导航到下一页,我将 textview 图像保存到 base64 编码的字符串中。在这里,我调用方法 encodeImageToString(Drawable d) 并将图像转换为字符串并将其存储在 JSON 字符串中 - 一旦用户导航回页面,我从 JSON 字符串中检索字符串,然后调用 decodeStringToImage(String s) 以取回 Drawable . 然后我将该 Drawable 显示到 textview 中。
问题是当图像重新加载到文本视图中时,质量会降低。每次重新加载都会降低质量。此外,当我检查了在 encodeImageToString() 中显示的字节数组大小时,它不断增加。
有人可以建议我在这里是否缺少任何东西。将图像重新加载到字符串,然后再将图像重新加载回图像应该不会影响图像的质量或大小。但在这种情况下并非如此。