How to encode an animated GIF in Java, using ImageWriter and ImageIO? - java

I've looked all over the place, but can't seem to find any easy to understand explanation. (I've found classes and methods written by other Java users that can do this, but I'm hoping to write my own.)

Here is the createImage() method of GIFanim. Perhaps that will give you a start.
public byte[] createImage() throws Exception {
ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
iw.setOutput(ios);
iw.prepareWriteSequence(null);
int i = 0;
for (AnimationFrame animationFrame : frameCollection) {
BufferedImage src = animationFrame.getImage();
ImageWriteParam iwp = iw.getDefaultWriteParam();
IIOMetadata metadata = iw.getDefaultImageMetadata(
new ImageTypeSpecifier(src), iwp);
configure(metadata, "" + animationFrame.getDelay(), i);
IIOImage ii = new IIOImage(src, null, metadata);
iw.writeToSequence(ii, null);
i++;
}
iw.endWriteSequence();
ios.close();
return os.toByteArray();
}
Note that this is a very naïve implementation, that produces images that are significantly larger than can be made with a library that compresses the color palette and performs other optimizations. Implementing a library like that would be a significant task.

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.

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);

How to decompress an image stored using stenography? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am currently doing project related to "image steganography" in Java, for that I want to compress and decompress the secret image. I have done the compression part. But I don't know how to perform the decompression part.
I have compressed the JPEG image using the following code:
public class CompressJPEGFile {
public static void main(String[] args) throws IOException {
File imageFile = new File("C:\\Users\\user\\Desktop\\encryption\\d.jpg");
File compressedImageFile = new File("C:\\Users\\user\\Desktop\\encryption\\compress.jpg");
InputStream is = new FileInputStream(imageFile);
OutputStream os = new FileOutputStream(compressedImageFile);
float quality = 0.5f;
BufferedImage image = ImageIO.read(is);
// get all image writers for JPG format
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
if (!writers.hasNext())
throw new IllegalStateException("No writers found");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
//associated stream and image metadata and thumbnails to the output
writer.write(null, new IIOImage(image, null, null), param);
// close all streams
is.close();
os.close();
ios.close();
writer.dispose();
}
}
I have written the code for decompression. Is the code right if I am not considering the quality of image?
public static void decompress() throws FileNotFoundException {
try {
File compressedImageFile = new File("C:\\Users\\user\\Desktop\\encryption\\compressnew.jpg");
File imageFile = new File("C:\\Users\\user\\Desktop\\encryption\\dnew.jpg");
InputStream is = new FileInputStream(compressedImageFile);
OutputStream os = new FileOutputStream(imageFile );
BufferedImage image = ImageIO.read(is);
// get all image writers for JPG format
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
if (!writers.hasNext()) {
throw new IllegalStateException("No writers found");
}
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
writer.write(null, new IIOImage(image, null, null), param);
//associated stream and image metadata and thumbnails to the output
is.close();
os.close();
ios.close();
writer.dispose();
} catch (IOException ex) {
Logger.getLogger(CompressJPEGFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
I think you are looking for a lossless a compression scheme that is such that you can retrieve a secret from steganography. That means you need to move away from jpg as your compression format - it is lossy. That means that once you have put your secret + cover image through the jpg compression, the original cannot be recovered by a simple 'decompression' call at the other end, i.e. the JPEG compression algorithm is not reversible.
You ask in comments about libraries for compression / decompression rather than steganography. You are already using one in your code example (ImageIO). If you want to take your original image and transcode it to PNG (i.e. lossless compression), ImageIO can do that simply - see this question for details. JAI is commonly used if you need more advanced features. The PNG format offers a lossless compression option.
EDIT:
some code to show using ImageIO using PNG format as requested by OP in comments. By default ImageIO uses compression when you write PNG's. At the receive end, simply read the PNG, you get the original back.:
public class JPEGFileToPNG {
public static void main(String[] args) throws IOException {
File imageFile = new File("C:\\Users\\user\\Desktop\\encryption\\d.jpg");
File compressedImageFile = new File("C:\\Users\\user\\Desktop\\encryption\\compress.png");
BufferedImage image = ImageIO.read(imageFile.toURI().toURL());
ImageIO.write(image, "png", compressedImageFile);
}
P.S. There are two levels at which to answer your question. At the more advanced (maybe research) level - people do work on using the actual errors introduced by JPG encoding to encode the secret in steganography (e.g. http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=1357167&tag=1) From the wording of your question, I don't think this is what you want, but it might be. In which case, your task is quite hard (writing a JPEG encoder / decoder and adapting it to hide secrets in the encoding table), but it has been done (e.g. this paper describes the method).

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