首页 > 解决方案 > 在 Java 中将 int 数组保存为图像时出现问题

问题描述

我试图通过首先将其数据元素作为字节操作,然后将其保存为 RGB 来操作图像。图像尺寸为 320x320x3 (rgb)。

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.IntBuffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

class sobel_java {
    public static void main(String args[]){
        
        BufferedImage image = null;
        try{
            image = ImageIO.read(new File("butterfinger.jpg"));
            final byte[] image_pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
            final int image_height = image.getHeight();
            final int image_width = image.getWidth();
            System.out.println(image_height);
            System.out.println(image_width);
    
            BufferedImage out_image = new BufferedImage(image_width, image_height, BufferedImage.TYPE_INT_RGB);
            /* Create an int array that contains image_pixels. */   
            IntBuffer intBuf = ByteBuffer.wrap(image_pixels).order(ByteOrder.BIG_ENDIAN).asIntBuffer(); 
            int[] array = new int[intBuf.remaining()];
            intBuf.get(array);
            /* Write the int array to BufferedImage. */
            out_image.getRaster().setDataElements(0, 0, image_width, image_height, array);
            /* Save the image. */
            ImageIO.write(out_image, "jpg", new File("out.jpg"));
            
        
    }catch(IOException e){
        System.out.println(e);
    }
    }
}

在运行时,我收到以下错误,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: arraycopy: last source index 77120 out of bounds for int[76800]
    at java.base/java.lang.System.arraycopy(Native Method)
    at java.desktop/sun.awt.image.IntegerInterleavedRaster.setDataElements(IntegerInterleavedRaster.java:425)
    at sobel_java.main(sobel_java.java:30)

标签: java

解决方案


您正在使用int数组。那么每个像素占用4个字节;RGB 覆盖 3 个 em,第 4 个被丢弃。这样,它是 1 int = 1 像素,而不是一些奇怪的打包算法。

通过不使用 int 数组或手动注入第 4 个忽略字节来修复它。


推荐阅读