BufferedImage with Transparent PNG - java

I'm uploading a PNG with a transparent background to a Java server using the below code
byte[] imageData = Base64.decodeBase64(encodedImage);
ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
BufferedImage bufferedImage = ImageIO.read(bais);
BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.OPAQUE, null);
Scene scene = sceneService.getScene(sceneId);
java.io.File file = new java.io.File(Constants.TEMP_DIR_PATH
+ UUID.randomUUID().toString() +".png");
ImageIO.write(newBufferedImage, "PNG", file);
I can't seem to set the background as transparent, it has to have a color?
Anyway to have a transparent background?

Use TYPE_INT_ARGB instead of TYPE_INT_RGB

Related

compress transparent png image to jpg give black background java

compress transparent png image to jpg give black background
I want white background instead of black
public static byte[] getBitMapBytes(Bitmap bmp, int quality) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, quality, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
fos = new FileOutputStream(f);
fos.write(getBitMapBytes(compressedImage, 60));
Got the answer :
Bitmap newBitmap = Bitmap.createBitmap(image.getWidth(),
image.getHeight(), image.getConfig());
Canvas canvas = new Canvas(newBitmap);
canvas.drawColor(Color.WHITE);
Rect dest = new Rect(0, 0, image.width, image.height);
Rect src = new Rect(0, 0, image.width, image.height);
canvas.drawBitmap(bmp, src, dest, null);
This is a normal behavior. Jpeg doesn't manage transparency.
You can use this kind of lib if you just want to reduce the size of the image:
http://objectplanet.com/pngencoder/ or online https://tinypng.com/

Converting a color image to grayscale is showing black image in java

I am trying to convert an image to gray scale image using Java. The problem here is, when I am trying to save that image after converting into gray scale it is showing a black image. I am little unaware of this image conversions. I would like to know why it is not working, and your answers will help me in my project. Thank you.
BufferedImage image = ImageIO.read(fileContent);
File outputFile = new File(date1);
ImageIO.write(image1, "png", outputFile);
(This is the color image obtained from html page, and it is working properly. And when I am trying to display/save this image, color image is visible. But the problem arises when the below code is used to convert color image to gray scale image.)
BufferedImage image1 = new BufferedImage(width, height,BufferedImage.TYPE_BYTE_GRAY);
Graphics graphics = image1.getGraphics();
graphics.drawImage(image, 0, 0, null);
graphics.dispose();
File outputFile = new File(date1);
ImageIO.write(image1, "png", outputFile);
There are color space conversion issues. You can manually convert each pixel of the output image to grayscale and set the pixels of the output image this way:
int gray = red * 0.299 + green * 0.587 + blue * 0.114
or use the ColorConvertOp class to do the conversion for you:
BufferedImage in = ImageIO.read(inputFile);
BufferedImage out = new BufferedImage(in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB);
ColorConvertOp op = new ColorConvertOp(in.getColorModel().getColorSpace(), ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
op.filter(in, out);
ImageIO.write(out, "png", outputFile);

8 bit gray scale image byte array to jpg

I am trying to convert a 8 bit gray scale image byte array to jpg image format in java.
static byte[] bytes = new byte[]{126, 126, 127, -128};
public static void main(String[] args) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = (ImageReader) readers.next();
Object source = bis;
ImageInputStream iis = ImageIO.createImageInputStream(source);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
Image image = reader.read(0, param);
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(image, null, null);
File imageFile = new File("C:\\newrose3.jpg");
ImageIO.write(bufferedImage, "jpg", imageFile);
System.out.println(imageFile.getPath());
}
I have bytes having image data and I want to convert it into readable image format in java.
Assuming bytes is supposed to be pixel data, you should create an image from those bytes, then write it out as JPEG.
Something like:
// Create an image type grayscale
BufferedImage image = new BufferedImage(2, 2, BufferedImage.TYPE_BYTE_GRAY);
// Get the backing pixels, and copy into it
byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(bytes, 0, data, 0, bytes.length);
// Write it out:
ImageIO.write(image, "jpg", new File("yourPathHere");

Java ARGB to JPG

How can I save BufferedImage with TYPE_INT_ARGB to jpg?
Program generates me that image:
And it's OK, but when I save it in that way:
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(byteStream);
try {
ImageIO.write(buffImg, "jpg", bos);
// argb
byteStream.flush();
byte[] newImage = byteStream.toByteArray();
OutputStream out = new BufferedOutputStream(new FileOutputStream("D:\\test.jpg"));
out.write(newImage);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The result is:
Understand that this is due to the alpha layer, but don't know how to fix it. Png format does not suit me, need jpg.
OK!
I've solved it.
Everything was pretty easy. Don't know is it a good decision and how fast it is. I have not found any other.
So.. everything we need is define new BufferedImage.
BufferedImage buffImg = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = buffImg.createGraphics();
// ... other code we need
BufferedImage img= new BufferedImage(buffImg.getWidth(), buffImg.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
g2d.drawImage(buffImg, 0, 0, null);
g2d.dispose();
If there any ideas to improve this method, please, your welcome.
Images having 4 color channels should not be written to a jpeg file. We can convert between ARGB and RGB images without duplicating pixel values. This comes in handy for large images. An example:
int a = 10_000;
BufferedImage im = new BufferedImage(a, a, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = im.createGraphics();
g.setColor(Color.RED);
g.fillRect(a/10, a/10, a/5, a*8/10);
g.setColor(Color.GREEN);
g.fillRect(a*4/10, a/10, a/5, a*8/10);
g.setColor(Color.BLUE);
g.fillRect(a*7/10, a/10, a/5, a*8/10);
//preserve transparency in a png file
ImageIO.write(im, "png", new File("d:/rgba.png"));
//pitfall: in a jpeg file 4 channels will be interpreted as CMYK... this is no good
ImageIO.write(im, "jpg", new File("d:/nonsense.jpg"));
//we need a 3-channel BufferedImage to write an RGB-colored jpeg file
//we can make up a new image referencing part of the existing raster
WritableRaster ras = im.getRaster().createWritableChild(0, 0, a, a, 0, 0, new int[] {0, 1, 2}); //0=r, 1=g, 2=b, 3=alpha
ColorModel cm = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).getColorModel(); //we need a proper ColorModel
BufferedImage imRGB = new BufferedImage(cm, ras, cm.isAlphaPremultiplied(), null);
//this image we can encode to jpeg format
ImageIO.write(imRGB, "jpg", new File("d:/rgb1.jpg"));

Java: How To Convert Image to Byte[]

I'm having an image in Database in bytearray format. I want to display on browser. I don't know how to write Image using OutputStream. Here is my code.
byte[] imageInBytes = (byte[]) obj; // from Database
InputStream in = new ByteArrayInputStream(imageInBytes);
Image img = ImageIO.read(in).getScaledInstance(50, -1, Image.SCALE_SMOOTH);
OutputStream o = resp.getOutputStream(); // HttpServletResponse
o.write(imgByte);
You may try something like this:
File f=new File("image.jpg");
BufferedImage o=ImageIO.read(f);
ByteArrayOutputStream b=new ByteArrayOutputStream();
ImageIO.write(o, "jpg", b);
byte[] img=b.toByteArray();
You have to set the content type of the response to be an image type that you are sending.
Suppose your image was stored when it was a jpeg. then,
OutputStream o = resp.getOutputStream(); // HttpServletResponse
o.setContentType("image/jpeg");
o.write(img.getBytes() /* imgByte */);
would send the browser an image. ( The browser understands from the header information that the following information you just sent it, is a jpeg image. )
You could try using ImageIO.write...
ImageIO.write(img, "jpg", o);
But this will require you to use BufferedImage when reading...
BufferedImage img = ImageIO.read(in);
You could then use AffineTransform to scale the image...
BufferedImage scaled = new BufferedImage(img.getWidth() / 2, img.getHeight() / 2, img.getType());
Graphics2D g2d = scaled.createGraphics();
g2d.setTransform(AffineTransform.getScaledInstance(0.5, 0.5));
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
img = scaled;
This, obviously, only scales the image by 50%, so you'll need to calculate the required scaling factor based on the original size of the image against your desired size...
Take a look at Java: maintaining aspect ratio of JPanel background image for some ideas on scaling images...

Categories