i have 2D array( it's only 1 -0 values) but its type is int[][].
Now i want to convert that array into image ( binary image black and white). But i couldn't find suitable answer for my question. I have searched google and this website. Can anyone help me??
I have tried this following code, but it
String path = "C:\\Users\\Cyrus\\Desktop\\test.jpg";
BufferedImage image = new BufferedImage(b.length, b[0].length, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < b.length; x++) { // b is my 2D array
for (int y = 0; y < b[x].length; y++) {
image.setRGB(x, y, b[x][y]);
}
}
File ImageFile = new File(path);
try {
ImageIO.write(image, "jpg", ImageFile);
} catch (IOException e) {
e.printStackTrace();
}
// after i modify my code
String path = "C:\\Users\\Cyrus\\Desktop\\test.jpg";
BufferedImage image = new BufferedImage(a.length, a[0].length, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < a.length; x++) {
for (int y = 0; y < a[x].length; y++) {
int value ;
if(a[x][y]==1) value = new Color(255,255,255).getRGB();
else value = new Color(0,0,0).getRGB();
image.setRGB(x, y, value);
}
}
File ImageFile = new File(path);
try {
ImageIO.write(image, "jpg", ImageFile);
} catch (IOException e) {
e.printStackTrace();
}
But it return wrong image
Can you be more specific on the result you get? Did it throw some exceptions? or the program finished normally but didn't produce the result you want?
You should notice that here you want to work with binary image, then is there any specific reason to choose JPG? As I know, JPG is not a native representation of color triplet RGB (as bmp for example). a jpeg file is a "container" of data sequence, in which there are a lot of information in its header (EXIF, QT,...), marked by markers. To deal with pixel value "directly" as in your array, the data sequence in jpg file must be "decoded", then after you play it the image, the main image data will be "encoded" again to be jpg stream.
To play directly with pixel value, I suggest you work with other formats (such as TGA, png,...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.