我需要做的是我有一個輸入影像檔案,我需要將其更改為用戶的引數。例如,如果用戶想讓它變暗 0,首先我用它們的 RGB 值獲取所有像素并將它們存盤在 2D 陣列中。下面給出了示例陣列。
114 121 140 //Pixel 1
114 121 140 //Pixel 2
114 121 140 //Pixel 3
.
.
.
50 57 83 //Pixel 2073601
之后我覆寫了 RGB 值(在我們的例子中,如果 RGB 值為 10:10:10,新值將為 7:7:7)。從那時起一切都很好。但是現在我在使用我的新資訊陣列創建 output.jpg 檔案時遇到了一些困難。當我運行我的函式時,它不會創建任何 output.jpg 檔案。這是我的功能。
public static void createFinalImage(int height, int width, String[][] rgbArray, String outputFile) {
BufferedImage img;
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
File f;
for (int y = 0; y < height; y ) {
for (int x = 0; x < width; x ) {
String[] data = rgbArray[y][x].split(" ");
int red = Integer.parseInt(data[0]);
int green = Integer.parseInt(data[1]);
int blue = Integer.parseInt(data[2]);
int rgb = new Color(red,green,blue).getRGB();
img.setRGB(x,y,rgb);
}
}
try
{
f = new File(outputFile);
ImageIO.write(img, "jpg", f);
}
catch(IOException e)
{
System.out.println("Error: " e);
}
}
我無法理解問題是什么以及為什么我無法使用此功能獲得更暗的影像。(我知道總是有更簡單和基本的方法來做到這一點,但這是一個多執行緒任務,我必須像我解釋的那樣做。)如果有人幫助我,我將不勝感激。
uj5u.com熱心網友回復:
這些ImageIO.write(...)方法回傳一個boolean指示是否安裝了可以以給定格式寫入影像的插件。檢查此值是一種很好的做法。雖然始終安裝了 JPEG 插件,但在最新版本的 Java 中,JPEG 插件不再支持帶有 alpha 通道的影像。大多數其他軟體無論如何都不支持 4 通道 RGBA JPEG,所以這不是一個很大的損失......
您所需要的只是更改BufferedImage.TYPE_INT_ARGB為沒有 alpha 的型別,例如BufferedImage.TYPE_INT_RGB或TYPE_3BYTE_BGR,一切都會起作用。無論如何,您似乎并沒有使用 alpha 通道。
重要的變化:
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y ) {
for (int x = 0; x < width; x ) {
// Manipulate pixels
}
}
try {
File f = new File(outputFile);
if (!ImageIO.write(img, "JPEG", f)) {
System.err.println("No plugin to write " img " in JPEG format to " f);
}
}
catch (IOException e) {
System.out.println("Error: " e);
}
uj5u.com熱心網友回復:
正如@HaraldK 所說,在我的函式中我BufferedImage.TYPE_INT_ARGB用作引數。但由于我沒有 alpha 值,我只是將其更改為BufferedImage.TYPE_INT_RGB. 下面給出了修改后的功能,它可以正常作業。
public static void createFinalImage(int height, int width, String[][] rgbArray, String outputFile) {
BufferedImage img;
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
File f;
for (int y = 0; y < height; y ) {
for (int x = 0; x < width; x ) {
String[] data = rgbArray[y][x].split(" ");
int red = Integer.parseInt(data[0]);
int green = Integer.parseInt(data[1]);
int blue = Integer.parseInt(data[2]);
int rgb = new Color(red,green,blue).getRGB();
img.setRGB(x,y,rgb);
}
}
try
{
f = new File(outputFile);
ImageIO.write(img, "jpg", f);
}
catch(IOException e)
{
System.out.println("Error: " e);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/363364.html
標籤:爪哇 图片 图像处理 javax.imageio
