用Java绘制像素图像 [英] Painting pixels images in Java
问题描述
哪种方法是使用java创建像素图像的最佳方法。
说,我想创建一个尺寸为200x200的像素图像,总共为40.000像素。如何从随机颜色创建像素并将其渲染到JFrame上的给定位置。
Which method is the best way to create a pixel image with java. Say, I want to create a pixel image with the dimensions 200x200 which are 40.000 pixels in total. How can I create a pixel from a random color and render it at a given position on a JFrame.
我试图创建一个只创建像素的自己的组件但是如果我使用for循环创建这样一个250,000倍的像素,这似乎不是非常高效将每个实例添加到JPanels布局。
I tried to create a own component which just creates pixel but it seems that this is not very performant if I create such a pixel a 250.000 times with a for-loop and add each instance to a JPanels layout.
class Pixel extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(getRandomColor());
g.fillRect(0, 0, 1, 1);
}
}
推荐答案
你不需要为此创建一个类。 Java已经拥有优秀的 BufferedImage 类这正是你所需要的。这是一些伪代码:
You do not need to create a class for this. Java already has the excellent BufferedImage class that does exactly what you need. Here is some pseudo-code:
int w = 10;
int h = 10;
int type = BufferedImage.TYPE_INT_ARGB;
BufferedImage image = new BufferedImage(w, h, type);
int color = 255; // RGBA value, each component in a byte
for(int x = 0; x < w; x++) {
for(int y = 0; y < h; y++) {
image.setRGB(x, y, color);
}
}
// Do something with image
这篇关于用Java绘制像素图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!