-2
- 我想將像素矩陣轉換成圖像,但它不工作。誰能幫我?以下是代碼。在這裏,我添加了一個打印語句來檢查它是否正在運行,但它也沒有執行。任何人都可以幫我在這裏
- 這是給問題的代碼。
- 這是完整的代碼。
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.image.PixelGrabber;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public final class Util {
/**
* Converts a java.awt.Image into an array of pixels
*/
public static int[] convertToPixels(Image img) {
int width = img.getWidth(null);
int height = img.getHeight(null);
int[] pixel = new int[width * height];
PixelGrabber pg = new PixelGrabber(img, 0, 0, width, height, pixel, 0, width);
try {
pg.grabPixels();
} catch (InterruptedException e) {
throw new IllegalStateException("Error: Interrupted Waiting for Pixels");
}
if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
throw new IllegalStateException("Error: Image Fetch Aborted");
}
return pixel;
}
public static Image getImageFromArray(int[] pixels, int width, int height) throws IOException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
WritableRaster raster = (WritableRaster) image.getData();
raster.setPixels(0, 0, width, height, pixels);
File output = new File("C:\\out.png");
ImageIO.write(image, "png", output);
System.out.print("written");
return image;
}
public static void main(String args[]) throws IOException {
int width, height;
BufferedImage source = ImageIO.read(new File(args[0]));
width = source.getWidth();
height = source.getHeight();
// Util obj = new Util();
Util.getImageFromArray(convertToPixels(source), width, height);
}
}
@DontKnowMuchButGettingBetter我在這裏粘貼完整的代碼。輸出不會到來,即它不會在任何地方創建名爲out.png的文件。 –
你的主要目標是什麼?從文件創建圖像? – Nikolay
是的,我想嘗試將像素數組轉換爲圖像並寫入它@Nikolay –