I have a problem with regards to changing my PNG image to grayscale. I wanted to make a method that would accept byte[] image as a parameter and return back as a newly modified grayscale image as byte[] also.
I found some links that make images grayscale with JPEG images using below snippet.
private byte[] makeItGray(byte[] img, String contentType) throws IOException, Exception{
InputStream in = new ByteArrayInputStream(img);
BufferedImage bimg = ImageIO.read(in);
for(int y=0; y < bimg.getHeight(); y++){
for(int x=0; x < bimg.getWidth(); x++){
Color color = new Color(bimg.getRGB(x,y));
int graylevel = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
int r = graylevel;
int g = graylevel;
int b = graylevel;
int rgb = ( r<<16 ) | ( g<<8 ) | b;
bimg.setRGB(x, y, rgb);
}
}
in.close();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if(contentType.equals(MediaType.IMAGE_PNG_VALUE)){
ImageIO.write(bimg, "png", baos);
System.out.println("PNG!!!");
}
else if(contentType.equals(MediaType.IMAGE_JPEG_VALUE)){
ImageIO.write(bimg, "jpg", baos);
}
else
throw new Exception();
baos.flush();
byte[] grayImage = baos.toByteArray();
baos.close();
return grayImage;
}
My references were on below : How can I use ImageJ as a library for a separate Java application? https://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/
It works on JPEG images but on PNG, it sends me a transparent image.
// converting orig image to grayscale in byte[]
imageBytes = makeItGray(imageBytes, file.getContentType());
Path path = Paths.get("some path here that would overwrite existing image");
Files.write(path, imageBytes);
When I try to open the image manually to check if it is grayscale, it gives me transparent image or no image is showing but not null since it returns byte[] data. I was wondering if the above method is ok with PNG formats?
Please let me know for any questions. Thanks!