[英]java - how to make an image using setRGB?
我有2D數組以保持顏色分量值:
p[pixel_value][red]
p[pixel_value][green]
p[pixel_value][blue]
我只是不知道如何使用它們來制作圖像。
我讀了有關setRGB的文章 ,我了解的是我應該將所有這些混合在一起成為RGBArray。 那怎么做呢?
沒有setRGB可以制作圖像嗎? 我需要一些解釋。
setRGB()
方法可用於設置現有圖像的像素顏色。 您可以使用2D數組中存儲的值打開一個已經存在的圖像並設置其所有像素。 您可以這樣做:
BufferedImage img = ImageIO.read(new File("image which you want to change the pixels"));
for(int width=0; width < img.getWidth(); width++)
{
for(int height=0; height < img.getHeight(); height++)
{
Color temp = new Color(p[pixel_value][red], p[pixel_value][green], p[pixel_value][blue]);
img.setRGB(width, height, temp.getRGB());
}
}
ImageIO.write(img, "jpg", new File("where you want to store this new image"));
這樣,您可以遍歷所有像素並相應地設置其顏色。
注意:這樣,您將丟失原始圖像。 這只是我所知道的一種方式。
您需要的是BufferedImage
。 如果要使用RGB,請創建一個TYPE_3BYTE_BGR
類型的BufferedImage
,並指定寬度和高度。
速覽:
BufferedImage子類描述了具有圖像數據可訪問緩沖區的Image。
然后,調用getRaster()
方法以獲取WritableRaster
速覽:
此類擴展了Raster以提供像素寫入功能。
然后,使用setPixel(int x, int y, double[] dArray)
方法設置像素。
更新:
如果您只想讀取圖像,請使用ImageIO.read(File f)
方法。 它使您僅需一個方法調用即可讀取圖像文件。
SSCCE有點:
BufferedImage img = null;
try {
img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}
您要手動設置RGB值嗎?
您需要知道,由於int
是32位的,因此它包含所有4個rgb值(透明性為1)。
xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
^Alpha ^red ^green ^blue
您可以通過使用二進制算術來使用4個int值:
int rgb = (red << 16) && () (green << 8) & (blue);
bufferedImage.setRGB(x, y, rgb);
在上面,您還可以根據需要添加Alpha
。 您只需將二進制代碼“推送”到正確的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.