In my Java application I would like to download a JPEG, transfer it to a PNG and do something with the resulting bytes.
I am almost certain I remember a library to do this exists, I cannot remember its name.
This is what I ended up doing, I was thinking toooo far outside of the box when I asked the question..
// these are the imports needed
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
// read a jpeg from a inputFile
BufferedImage bufferedImage = ImageIO.read(new File(inputFile));
// write the bufferedImage back to outputFile
ImageIO.write(bufferedImage, "png", new File(outputFile));
// this writes the bufferedImage into a byte array called resultingBytes
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOut);
byte[] resultingBytes = byteArrayOut.toByteArray();
ImageIO can be used to load JPEG files and save PNG files (also into a ByteArrayOutputStream if you don't want to write to a file).
javax.imageio should be enough.
Put your JPEG to BufferedImage, then save it with:
File file = new File("newimage.png");
ImageIO.write(myJpegImage, "png", file);
BufferedImage bufferGambar;
try {
bufferGambar = ImageIO.read(new File("ImagePNG.png"));
// pkai type INT karna bertipe integer RGB bufferimage
BufferedImage newBufferGambar = new BufferedImage(bufferGambar.getWidth(), bufferGambar.getHeight(), BufferedImage.TYPE_INT_RGB);
newBufferGambar.createGraphics().drawImage(bufferGambar, 0, 0, Color.white, null);
ImageIO.write(newBufferGambar, "jpg", new File("Create file JPEG.jpg"));
JOptionPane.showMessageDialog(null, "Convert to JPG succes YES");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Related
I have the following code, that transforms an Image into a byte[]:
BufferedImage image = ImageIO.read(new File("Path/To/Custom/image.jpg"));
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
ImageIO.write(image, "jpg", baos);
byte[] imageBytes = baos.toByteArray();
This code works totally fine, at least I get a byte array containing different values. But now comes the difficult part: The byte[] has to be reconstructed into am image again. The following code does not work, ImageIO.read(...) returns null. I read the documentation, but still I can not find out what to change so that the code functions in the way I want it to.
ByteArrayInputStream ba = new ByteArrayInputStream(imageBytes);
BufferedImage image = ImageIO.read(ba);
//image is always null, no matter what the stream or the byte values are.
import java.io.ByteArrayOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ByteArrayToImage {
public static void main(String args[]) throws Exception {
BufferedImage bImage = ImageIO.read(new File("sample.jpg"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bImage, "jpg", bos );
byte [] data = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
BufferedImage bImage2 = ImageIO.read(bis);
ImageIO.write(bImage2, "jpg", new File("output.jpg") );
System.out.println("image created");
}
}
Modify this to your needs.
Try reading an ByteArrayInputStream on ImageIO.read() not an ByteArrayOutputstream.
I have a BLOB that is retrieved from a MySQL database as follows:
Blob imageBlob;
while (rs.next()) {
imageBlob= rs.getBlob("face");
}
after that my imageBlob is something like this: data:image/png;base64,iVBORw0KGgoAAAANSUhE................
I've been googling around but I haven't found any solution to my problem: how do I create an image file and save it on the disk from this BLOB?
imageBlob is storing the base64 representation of your image data. For storing that onto your disk you need to decode that base64 representation into the original binary format representation.
// Imports required
import java.util.Base64
import java.io.ByteArrayInputStream;
import java.io.File;
import javax.imageio.ImageIO;
String imageData = "data:image/png;base64,iVBORw0KGgoAAAANSUhE....";
String base64Data = imageData.split(",")[1]
byte[] decodedBytes = Base64.getDecoder().decode(base64Data);
ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes);
BufferedImage image = ImageIO.read(bis);
File outputFile = new File("output.png");
ImageIO.write(image, "png", outputFile);
First convert the Blob to BuffededImage:
Blob aBlob = rs.getBlob("Photo");
InputStream is = aBlob.getBinaryStream(1, aBlob.length());
BufferedImage image=ImageIO.read(is);
Then BufferedImage to Image:
try {
// Retrieve Image
File outputfile = new File("saved.png");
ImageIO.write(image, "png", outputfile); // Write the Buffered Image into an output file
Image image = ImageIO.read(new File("saved.png")); // Opening again as an Image
} catch (IOException e) {
...
}
I am trying to read images from external directory and for that I am using
bufferedImage image=ImageIO.read(new File(imagefile));
jlabel.seticon(new imageicon(image));
and getting a drastic change in colors. I tried many other things like:
bufferedImage image=ImageIO.read(new File(imagefile));
bufferedImage img=new bufferedImage(image.getWidth(),image.getHeight(),bufferedImage.TYPE_INT_RGB);
and I tried:
img.setData(image.getData();
jlabel.seticon(new imageicon(image));
and I tried:
Iterator readers = ImageIO.getImageReadersByFormatName("JPEG");
ImageReader reader = null;
while(readers.hasNext()) {
reader = (ImageReader)readers.next();
if(reader.canReadRaster()) {
break;
}
}
ImageInputStream input = ImageIO.createImageInputStream(f);
reader.setInput(input);
Raster raster = reader.readRaster(0, null);
BufferedImage bi = new BufferedImage(raster.getWidth(), raster.getHeight(),
BufferedImage.TYPE_4BYTE_ABGR);
bi.getRaster().setRect(raster);
but result are still same
http://i.stack.imgur.com/jNVm0.jpg
Here is an example of the issue:
The minimal code for viewing is:
bufferedImage image=ImageIO.read(new File(imagefile));
jlabel.seticon(new imageicon(image));
lbitem.setIcon(im);
and for storing
File f = new File(s);
long size=f.length();
FileInputStream fis1=new FileInputStream(f);
FileOutputStream fos2=new FileOutputStream("src/image/"+tfpn.getText()+".jpg");
byte b[]=new byte[1000];
int r=0;
long count=0;
while(true)
{
r=fis1.read(b,0,1000);
fos2.write(b,0,1000);
count = count+r;
if(count==size)
break;
System.out.println(count);
}
What could be causing the bad colors?
This problem is cause by a mismatch between reading/writing (creating/using) an image
that contains alpha (transparency) but you are expecting it to contain no alpha (or the inverse).
For example, if your image is BufferedImage.TYPE_4BYTE_ABGR and you output it
to a file type that does not support alpha (transparency) , or you writer does not
support alpha, it will look like your sample after reading and displaying it.
Use type PNG (supports alpha channel) not JPG (does not support alpha channel)
I have a png file and tried to convert it to jpeg. But the resulting image has wrong colors with very big areas of pink. This is my code:
BufferedImage image = null
BufferedImage imageRGB = null
image = ImageIO.read(new ByteArrayInputStream(imageBytesPng))
imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB)
imageRGB.setData(image.getData())
ByteArrayOutputStream baos=new ByteArrayOutputStream()
ImageIO.write(imageRGB, "jpeg", baos)
baos.flush()
def outImage = baos.toByteArray()
baos.close()
return outImage
What can I change to make the image colors apear as in the png file?
InputStream pngInputStream = ...
OutputStream jpgOutputStream = ...
BufferedImage image = ImageIO.read(pngInputStream));
ImageIO.write(image, "jpeg", jpgOutputStream);
Try this all the best..
import javax.media.jai.*;
public class jai_png_jpg
{
public static void main(String[] args)throws Exception
{
String filename="input_png.png";
//Read input PNG as a PlanarImage file
PlanarImage inputfile = JAI.create("fileload", filename);
//write output in JPG Format
JAI.create("filestore",inputfile,"jai_jpg_output.jpg","JPEG"); } }
I use the following method for converting images to jpg. The problem with my solution is that it will reduce the quality to much.
What is a good way to maintain quality of the image, while reducing the file size?
def convertToJpg(currentImage) {
try {
InputStream inStreamCrop = new ByteArrayInputStream(currentImage)
BufferedImage bufferedImage = ImageIO.read(inStreamCrop)
// create a blank, RGB, same width and height, and a white background
BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
ByteArrayOutputStream baos=new ByteArrayOutputStream()
// write to jpeg file
ImageIO.write(newBufferedImage, "jpg", baos);
baos.flush()
def image = baos.toByteArray()
baos.close()
return image
} catch (IOException e) {
e.printStackTrace();
}
}
You can control the quality of the JPEG by getting an ImageWriter object and setting it through the parameters. For example:
import javax.imageio.stream.*
import javax.imageio.*
BufferedImage bufferedImage = ImageIO.read(new File("test.png"));
float quality = 0.9;
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
writer.setOutput(new FileImageOutputStream(new File("test.jpg")));
writer.write(null, new IIOImage(bufferedImage, null, null), param);
The quality parameter can range between 0 and 1, with 1 having the least compression. Try different values; I've found 0.9 is a good choice for low compression (but large file sizes).
Note that JPEG images are not supported with OpenJDK: ImageIO not able to write a JPEG file