Converting bitmap to byte array, to string, then all the way back

江枫思渺然 提交于 2019-12-10 22:06:55

问题


I have tried several different methods found in the java documentation, as well as several solutions from other SO questions and have successfully gotten a Bitmap to convert to a byte[] and back again.

The problem is that I now need to convert this byte[] to a String, then back to a byte[], then back to a Bitmap again. To recap what I need:

Bitmap -> byte[] -> String -> byte[] -> Bitmap

I know this sounds strange but what I'm trying to accomplish must be done this way. Below is what I have tried, if anyone could point out what I'm doing wrong I'd greatly appreciate it!

Bitmap bitmap = mv.getDrawingCache();

// Convert bitmap to byte[]
ByteArrayOutputStream output = new ByteArrayOutputStream(bitmap.getByteCount());
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
byte[] imageBytes = output.toByteArray();

// Convert byte[] to string
// I have also tried using Base64.encodeToString(imageBytes, 0);

String encodedString = new String(imageBytes);

// Convert string to byte[]
byte[] newImageBytes = encodedString.getBytes();

if (imageBytes == newImageBytes) {
    Toast.makeText(SignatureActivity.this, "SUCCESS!!", Toast.LENGTH_SHORT).show();
} else { // Sadly, we always get to this point :(
    Toast.makeText(SignatureActivity.this, "BOOO", Toast.LENGTH_SHORT).show();
}

// Convert byte[] back to bitmap
bitmap = BitmapFactory.decodeByteArray(newImageBytes, 0, newImageBytes.length);

Again, going Bitmap -> byte[] -> Bitmap was successful, but adding in the conversion to a String and back is causing the final Bitmap to write an image of 0kb.


回答1:


The problem is not in the conversion, but how you verify the result. using == to compare two arrays only returns true if they are the same array reference. Since you create a new array with byte[] newImageBytes = encodedString.getBytes(); This will always be false. See this question for reference.

On another note, if you are going to transfer or use the string in some way, it is probably better to use Base64.encodeToString(imageBytes, Base64.NO_WRAP); to get a string, and get it back with Base64.decode(encodedString, Base64.NO_WRAP).
You can also get the byte array without compressing it, with the copyPixelsToBuffer() method (see this question for an example).



来源:https://stackoverflow.com/questions/20621285/converting-bitmap-to-byte-array-to-string-then-all-the-way-back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!