【问题标题】:How to create a grayscale image using java如何使用java创建灰度图像
【发布时间】:2018-11-15 18:21:15
【问题描述】:
【问题讨论】:
标签:
java
image
pixel
grayscale
【解决方案1】:
要创建每个像素大小为 2x2 的图片,您必须缩放图像(因子 2)仅用于显示...或者如果您想创建图像,您必须手动创建图像并绘制比例因子为 2
int[] pixels = ... //we already have our gray scale pixels here
int widthOriginal = ... //size of original image
int heightOriginal = ...
//let's create an buffered Image twice the size
BufferedImage img =
new BufferedImage(2*widthOriginal, 2*heightOriginal, BufferedImage.TYPE_4BYTE_ABGR);
//we paint on the buffered image's graphic...
Graphics gr = img.getGraphics();
//we draw all pixels on the graphic
for(int y = 0; y < heightOriginal; y ++){
for(int x = 0; x < widthOriginal; x ++){
int index = y*widthOriginal + x;
int gray = pixels[index];
//to draw we first set the color
gr.setColor(new Color(gray));
//then draw the pixel
gr.drawRect(2*x, 2*y,2,2); //draw a 2x2 pixel instead of a 1x1 pixel
}
}
嗯 - 老实说,我写的代码完全是在我的脑海中,所以可能存在一些小的编译问题......但是该技术得到了正确的解释......