Android 将位图写入文件更改字节?

Android 将位图写入文件更改字节?,android,bitmap,Android,Bitmap,我用字节数组制作了一个位图。我想将位图保存到一个文件中。然后我想检索该位图并恢复原始字节数组。我以为我可以简单地保存文件,然后读取它,但显然字节是不同的 保存位图: // create the bitmap final Bitmap bitmap = Bitmap.createBitmap(width, newHeight, Bitmap.Config.ARGB_8888); ByteBuffer buffer = ByteBuffer.wrap(originalBytes); bitmap.c

我用字节数组制作了一个位图。我想将位图保存到一个文件中。然后我想检索该位图并恢复原始字节数组。我以为我可以简单地保存文件,然后读取它,但显然字节是不同的

保存位图:

// create the bitmap
final Bitmap bitmap = Bitmap.createBitmap(width, newHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(originalBytes);
bitmap.copyPixelsFromBuffer(buffer);
...
// save the bitmap to file
String dir_path = Environment.getExternalStorageDirectory().getAbsolutePath();
File dir = new File(dir_path);
if(!dir.exists())
{
    dir.mkdirs();
}
File file = new File(dir, "meh.png");
FileOutputStream fOut = null;
try {
    fOut = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
    fOut.flush();
    fOut.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
然后我读了这个文件

// read the file
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(file_path + "/" + "meh.png");

// get the bytes
ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount());
bitmap.copyPixelsToBuffer(buffer);
byte[] retrievedBytes = buffer.array();
当我比较originalBytes和retrievedBytes时,长度是相同的,但内容不同。我以为Bitmap.CompressFormat.PNG保证不压缩?我错过了什么

编辑:

下面是两个字节数组转换为十六进制的部分

原始字节十六进制:8D7D A111 DE1D 105F 0B58 86A0 5F4D 035A D9A6


检索到的字节十六进制:0406 0711 1F1D 105F 0B58 86A0 054D 035A 3C09…

请勿使用位图和位图工厂将字节数组保存到文件或在字节数组中加载文件。如您所见,这将更改字节

最好直接将字节数组保存到文件中。并直接在字节数组中加载文件的内容


也会快得多。

没有压缩并不意味着字节的格式/顺序是相同的:所以没有办法保持顺序?是否有其他方法保存/恢复字节数组?如果可能的话,我想把它保留为一张“可打开”的图片。你说的“可打开”是什么意思?如果位的顺序不正确,任何其他PNG查看器都无法获得正确的图像。我现在存储的PNG可以在Android gallery中打开。它正确地表示位图。只有当我在代码中读取它并检索字节时,它们才与使用的原始字节不匹配。我不知道如何解决这个问题。你能把两个数组的前两个字节的摘录作为十六进制值发布吗?只是为了验证问题是否真的是字节顺序。我想这是另一种选择。问题是,整个过程是图像加密的一部分。我想加密一个图像,将其存储在磁盘上,然后检索它来解密它。我想将加密字节数组保留为图像,因为它应该表示加密图像。