Java로 이미지 처리를하고 싶습니다. 시작하기 전에 필터 나 기타 작업을 수행하기 전에 이미지에 바이트 배열로 변환 한 다음 이미지로 변환하고 저장하여 저장 방법을 확인하십시오.Image to byte [] to Image
입력 이미지로 출력 이미지를 가져 오지 못하고 일부 출력물/데이터가 손실되어 출력이 다른 색상으로 보입니다.
제발 어떤 문제인지 말해주세요. 내가 무엇을 놓치고 있는지.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Ola {
BufferedImage img = null;
public void loadImage() {
try {
img = ImageIO.read(new File("/home/a/Pictures/Tux-vegeta.png"));
} catch (IOException e) {
System.out.println("image(s) could not load correctly, try changing the path");
}
}
public byte[] convertToArray() {
int w = img.getWidth();
int h = img.getHeight();
int bands = img.getSampleModel().getNumBands();
System.out.print(bands);
if (bands != 4) {
System.out.println("The image does not have 4 color bands");
}
byte bytes[] = new byte[4 * w * h];
int index = 0;
for(int y = 0; y < h; y++) {
for(int x = 0; x < w; x++) {
int pixel = img.getRGB(x, y);
int alpha = (pixel >> 24) & 0xFF;
int red = (pixel >> 16) & 0xFF;
int green = (pixel >> 8) & 0xFF;
int blue = pixel & 0xFF;
bytes[index++] = (byte) alpha;
bytes[index++] = (byte) red;
bytes[index++] = (byte) green;
bytes[index++] = (byte) blue;
}
}
return bytes;
}
public void convertToImage(byte[] bytes) {
try {
int w = 300;
int h = 300;
int index = 0;
BufferedImage resultPNG = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j ++) {
int pixel = (bytes[index] << 24) | (bytes[index + 1] << 16) | (bytes[index + 2] << 8) | (bytes[index + 3]);
resultPNG.setRGB(j, i, pixel);
index += 4;
}
}
File outputImage = new File("/home/a![enter image description here][1]/Pictures/test.png");
ImageIO.write(resultPNG, "png", outputImage);
} catch (IOException e) {
System.out.println("image write error");
}
}
public static void main(String[] args) {
Ola ola = new Ola();
ola.loadImage();
ola.convertToImage(ola.convertToArray());
}
}
/OutputStream 및 ImageIO – MadProgrammer