java - 在 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)
解决方案
您正在使用int
数组。那么每个像素占用4个字节;RGB 覆盖 3 个 em,第 4 个被丢弃。这样,它是 1 int = 1 像素,而不是一些奇怪的打包算法。
通过不使用 int 数组或手动注入第 4 个忽略字节来修复它。
推荐阅读
- python - 使用 eval() 动态生成 Tkinter 子顶级类
- performance - MATLAB 中 all(a(:,i)==a,1) 的更快替代方案
- expo - 有没有办法通过 Expo 管理的工作流程跟踪 Facebook 广告系列广告安装?
- c - bsearch 的比较回调函数只需要实现相等吗?
- c++ - 有没有办法查看用户输入是否与 C++ 中的变量名匹配?
- pytorch - PyTorch 中是否有深度常数卷积层选项?
- python - Python zipfile尝试除了不传递“zlib.error:解压缩数据时错误-3:无效距离太远”
- android - android可以成为USB设备的主机吗?
- swift - 按日期搜索笔记的模型
- php - lighthouse php 使用 eloquent 模型访问器和修改器