![](/img/trans.png)
[英]How to rotate a bufferedimage, then copy the bufferedImage into a pixel array
[英]Java BufferedImage: How do i copy an image properly n times by accessing the pixel - array?
我正在处理一个问题,这种问题是从我正在从事的项目中“分叉”出来的。 没有必要解决项目本身,但我提到起源是因为它是一种“奇怪的特定”任务。
我正在尝试从文件(8x8 像素)中读取一个小的 BufferedImage。 该图像的像素被写入一个整数数组,长度为 64(显然)。
然后,创建一个长度为 64*64 (=4096) 的新数组。 小数组的像素被复制到大数组中 64 次,每次到达末尾时将较小的索引重置为 0。
最后,我创建了一个宽度为 64 且高度为 64 的新 BufferedImage。然后将大数组设置为所述 BufferedImage 的 rgbArray。 代码如下:
public static void main(String[] args)throws IOException {
BufferedImage toCopy = ImageIO.read(new File("smallStripes.png"));
BufferedImage copiedNTimes = new BufferedImage(64, 64, BufferedImage.TYPE_BYTE_BINARY);
//copiedNTimes is to be the resulting image
Graphics2D g2d = (Graphics2D) copiedNTimes.getGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 64, 64);
int[] smallPixels = new int[64];
toCopy.getRGB(0, 0, 8, 8, smallPixels, 0, 8);
//copy the rgb array of read image into the 64 - array
int[] copied = copyNTimes(smallPixels, new int[64*64]);
copiedNTimes.setRGB(0, 0, 64, 64, copied, 0, 8);
//setting the rgb array of result image to the copied one
FileOutputStream fos = new FileOutputStream(new File("result.png"));
ImageIO.write(copiedNTimes, "png", fos);
}
static int[] copyNTimes(int[] small, int[] big){
//this method copies the small array into the larger one
//until the larger one is 'filled up'
int index = 0;
for(int x = 0 ; x < big.length; x++){
big[x] = small[index];
index++;
if(index == small.length)
index = 0;
}
return big;
}
它或多或少地像我预期的那样工作,但图像被写入“移位”:
小条纹.png:
结果.png:
我的问题是:
我怎么能做到条纹彼此“对齐”? 现在是,从左到右,8px 黑色,8px 白色,8px 黑色......等等。 为什么不是 64 px 黑色(新线) 64 px 白色(新线)等?
正如已经说过的,它奇怪地具体且过于简单化,因此我可以更好地描述它。
您拥有的代码使用 scanline=8 作为最后一个参数来设置 RGB 以及 copyNTimes 中的错误逻辑,这会导致您的剥离效果。 如果您希望将 8x8 像素图像作为 8x8 块重复为 64x64 像素图像,请使用此替换 setRGB 调用以将小图像重复为较大的图像:
for (int x = 0 ; x < 64 ; x += 8)
for (int y = 0 ; y < 64 ; y += 8)
copiedNTimes.setRGB(x, y, 8, 8, smallPixels, 0, 8);
或者用这个替换你的 setRGB 调用以首先构建更大的 int[] 并在一个步骤中应用它:
copiedNTimes.setRGB(0, 0, 64, 64, copied, 0, 64);
static int[] copyNTimes(int[] small, int[] big){
for(int x = 0 ; x < big.length; x++){
big[x] = small[8 * ((x / 64) % 8) + (x % 8)];
}
return big;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.