How to Convert jpeg image into jpeg2000 lossless compression image? - java

I am compressing a image using java.
I want to compress the image in jpeg2000 lossless.
Please suggest solution.
File imageFile = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg");
File compressedImageFile = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\decompjai.jpg");
InputStream is = new FileInputStream(imageFile);
OutputStream os = new FileOutputStream(compressedImageFile);
BufferedImage image = ImageIO.read(is);
// get all image writers for JPG format
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jp2k");
if (!writers.hasNext())
throw new IllegalStateException("No writers found");
ImageWriter writer = (ImageWriter) writers.next();
J2KImageWriter
J2KImageWriteParam jwp = (J2KImageWriteParam) writer.getDefaultWriteParam();
// J2KImageWriteParam jwp = new J2KImageWriteParam();
boolean lossless = true;
jwp.setLossless(lossless);
// jwp.setFilter(J2KImageWriteParam.FILTER_97);
if (!lossless) {
jwp.setEncodingRate(8.0 / 2);
}
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
writer.write(null, new IIOImage(image, null, null), jwp);
ios.flush();
ios.close();
} catch (IOException e) {
e.printStackTrace();
}
I am trying with the above code.

Check out this JPEG2000 Java Encoder/Decoder project. (you can find the source code here)

I'd first try javax.ImageIO as your system may have a provider for the JPEG2000 format.
Otherwise: http://www.deic.uab.cat/~francesc/ is apparently for java.

Related

Any Alternative to ImageIO.write to convert bufferedimage to GIF bytes (Faster than ImageIO)?

my problem is when using imageio.write i am seeing that is using hdd, also read about jDeli (but too expensive), Apache Commons, JAI that are much faster....
I wanna use the encoded bytes returned by routine... at a custom Remote Desktop Utility...
public static byte[] imageToJPEGByteArray(Image aImage, int width, int height, int qualityPercent) throws IOException {
byte[] imageBytes = new byte[0];
float quality = 75 / 100f;
BufferedImage destImage;
destImage = SwingFXUtils.fromFXImage(aImage, null);
// Output JPEG byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if(qualityPercent != -1) {
// Start to create JPEG with quality option
ImageWriter writer = null;
Iterator iter = ImageIO.getImageWritersByFormatName("gif");
if (iter.hasNext()) {
writer = (ImageWriter) iter.next();
}
ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
writer.setOutput(ios);
ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwparam.setCompressionQuality(quality);
writer.write(null, new IIOImage(destImage, null, null), iwparam);
ios.flush();
writer.dispose();
ios.close();
// Done creating JPEG with quality option
} else {
// This one line below created a JPEG file without quality option
ImageIO.write(destImage, "gif", baos);
}
baos.flush();
imageBytes = baos.toByteArray();
baos.close();
// Done
return imageBytes;
}
If you are saying that you've observed that this code appears to cause disk activity when saving to ByteArrayOutputStream perhaps you should try setting the ImageIO "use cache" flag to false:
ImageIO.setUseCache(false);
Javadoc for setUseCache says:
Sets a flag indicating whether a disk-based cache file should be used when creating ImageInputStream and ImageOutputStreams.

How to keep compressing a image with ImageWriter in JAVA?

I need to compress every image that is larger than 500 kbytes.
So, i'm trying to create a code that will test every compression quality until i get <= 500 kb, then i'll have the best quality with the lowest length.
My biggest problem here is that writer method from ImageWriter appends my new image to the old. So, if i have a 600kb image and write a new one with low quality, i'll have 600kb + probably 500kb (size of the new image) in the same .jpg file and with a low quality.
My code:
public byte[] imageCompressor(String filePath, String newFileName, String formatName) throws IOException {
File input = new File(filePath);
BufferedImage image = ImageIO.read(input);
File compressedImageFile = new File(newFileName);
String compressedWithFormat = compressedImageFile + "." + formatName;
OutputStream os = new FileOutputStream(compressedWithFormat);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatName);
ImageWriter writer = (ImageWriter) writers.next();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ImageIO.createImageOutputStream(baos));
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writer.write(null, new IIOImage(image, null, null), param);
float contador = 1f;
while (imageSizeChecker(compressedWithFormat) > 500) {
param.setCompressionQuality(contador -= 0.09f); // Change the quality value you prefer
writer.write(null, new IIOImage(image, null, null), param);
System.out.println(imageSizeChecker(compressedWithFormat));
writer.dispose();
}
writer.dispose();
return baos.toByteArray();
}
public Long imageSizeChecker(String filePath) {
File insertFile = new File(filePath);
Long fileSize = insertFile.length() / 1024;
return fileSize;
}
Also, i want to return the image in a byte array (as it follows), and i'm trying to send the image file on the parameter as a byte array (replacing String filepath for byte[] filepath)
You keep writing multiple images to the same ByteArrayOutputStream. To reset the output stream and discard the data between each image, you can use:
baos.reset();
There are several other problems -- such as inspecting a file you never write -- but if you're finding that appended data is the major problem, this seems to be why.

write the image to outputStream and not a file to update the entity in the database

The byte[] content is the content of the image in the database. So after getting it I am checking its size and in case of size of 2MB I am compressing it then I want to update the entity in the database.
Currently I am able to write the compressed image as a jpg file. How can write the image as Outputstream without the need of compressedImageFile? Then I want to convert it to byte array and update the entity in the database.
private void compressImage(byte[] content){
try {
InputStream inputStream = new ByteArrayInputStream(content);
BufferedImage image = ImageIO.read(inputStream);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter imageWriter = writers.next();
//With this two lines I can write the content to the file.
//File compressedImageFile = new File("C:\\Users\\photos\\temp\\image.jpg");
//OutputStream os = new FileOutputStream(compressedImageFile);
//OutputStream os = new OutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
imageWriter.setOutput(ios);
getLogger().info("ios: " + ios);
ImageWriteParam param = imageWriter.getDefaultWriteParam();
if (param.canWriteCompressed()) {
System.out.println("Yes it can write compress!");
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
String[] types = param.getCompressionTypes();
param.setCompressionQuality(0.5f);
System.out.println("canWriteCompressed is true");
}
imageWriter.write(null, new IIOImage(image, null, null), param);
getLogger().info("ios at the end: " + ios);
} catch (IOException e) {
e.printStackTrace();
}
}

this code works fine , but compression of png image is not happening

Code works fine for other formats of images but for .png compression is negligible or no compression at all
here is a sample how the image is loaded and saved
Or someone suggest me better way of compressing png image
This is myfirst question posted on stackoverflow. please ignore any mistakes
I have taken sample images from local folder
File input = new File("C:/Users/Public/Pictures/Sample Pictures/bz_nela19911.png");
InputStream is = new FileInputStream(input);
BufferedImage image = ImageIO.read(is);
File compressedImageFile = new File("C:/Users/Public/Pictures/Sample Pictures/me1.png");
OutputStream os =new FileOutputStream(compressedImageFile);
Iterator<ImageWriter>writers = ImageIO.getImageWritersByFormatName("png");
// works fine for other formats of images
ImageWriter writer = null;
while (writers.hasNext()) {
ImageWriter candidate = writers.next();
if (candidate.getClass().getSimpleName().equals("CLibPNGImageWriter")) {
writer = candidate; // This is the one we want
break;
}
else if (writer == null) {
writer = candidate;
}
}
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
if (param.canWriteCompressed()) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.1f);
}
writer.write(null, new IIOImage(image, null, null), param);

png file turn all black when compress to jpeg. Is it because PNG is lossless?

I have a piece of code that compress an jpg image with a certain quality, but when the image is png type, they all turn black. Any idea why and how to fix it? here is my code.
public void compressImage(String filename, ServletContext servletContext) {
//You first need to enumerate the image writers that are available to jpg
Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
//Then, choose the first image writer available
ImageWriter writer = (ImageWriter) iter.next();
//instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
//Set the compression quality
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(0.5f);
try {
BufferedImage img = ImageIO.read(new File(filename));
String destPath = "/Users/KingdomHeart/resources/scholar/compress/compress.jpg";
File file = new File(destPath);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(img, null, null);
writer.write(null, image, iwp);
writer.dispose();
}catch(IOException e){
}
}
This might have the answers you're looking for: Converting transparent gif / png to jpeg using java
The issue is likely that you're working with a PNG that has some transparency in it.

Categories

Resources