简体   繁体   English

Android更改原始PNG数据

[英]Android change raw PNG data

I have a PNG file in my project where I want to change some values at run time. 我的项目中有一个PNG文件,我想在运行时更改一些值。

    ByteArrayOutputStream output = new ByteArrayOutputStream();

    try {
        InputStream input = getIntro().getAssets().open("image.png");
        byte[] tmp = new byte[1024];
        int ret = 0;
        while ((ret = input.read(tmp, 0, 1024)) >= 0) {
            output.write(tmp, 0, ret);
        }
    } catch (IOException ex) {
        System.out.print(ex);
    }

    byte[] imgArray = output.toByteArray();

    imgArray[1000] = (byte) Color.red(Const.SOMEVALUE);

    return BitmapFactory.decodeByteArray(imgArray, 0, imgArray.length);

whatever I do in imgArray[1000] = (byte) Color.red(MyApplication.COLOR_BOARD_BG) line, I get an empty image. 无论我在imgArray[1000] = (byte) Color.red(MyApplication.COLOR_BOARD_BG)行中做什么,我都会得到一个空图像。 If I don't use that line and modify byte array manually it's OK, however anything I change (in the header or body) does not differ = blank image. 如果我不使用该行并手动修改字节数组就可以,但是我更改的任何内容(在标头或正文中)都不会不同=空白图像。

Actually I try to modify the palette information but here as an example I change the 1000th element which is some value within image data. 实际上,我尝试修改调色板信息,但在此作为示例,我更改了第1000个元素,该元素是图像数据中的某个值。

The PNG fileformat stores the image data in compressed form. PNG文件格式以压缩形式存储图像数据。 Changing just one byte somewhere probably invalidates an internal checksum, resulting in an invalid image, so you can't do that. 仅在某处更改一个字节可能会使内部校验和无效,从而导致图像无效,因此您不能这样做。 In addition to that, each PNG chunk is protected by a 32-bit CRC checksum , so any modification to any part of the file requires updating at least the checksum to the chunk you modify 除此之外, 每个PNG块都受32位CRC校验和保护 ,因此对文件任何部分的任何修改都至少需要将校验和更新为您修改的块

If you want to modify the pixels of the image it will be easier to decode the PNG data first, using libraries that are available to you, like BitmapFactory and Bitmap on Android. 如果要修改图像的像素,则可以使用可用的库(例如Android上的BitmapFactory和Bitmap)更轻松地首先对PNG数据进行解码。

Bitmap png = BitmapFactory.decodeFile(selectedImagePath);
png.setPixel(34,43,0xFFFF0000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM