Apache Commons Imaging - convert tiff to jpg - java

I need to convert a tiff image into a jpg one using Apache Commons Imaging.
I tried to but I can't figure out how to do it using this library.
final BufferedImage image = Imaging.getBufferedImage(new File(image));
final ImageFormat format = ImageFormats.JPEG;
final Map<String, Object> params = new HashMap<>();
return Imaging.writeImageToBytes(image, format, params);
Where image is my tiff file to be converted, but I get
org.apache.commons.imaging.ImageWriteException: This image format (Jpeg-Custom) cannot be written.
I don't understand what I'm doing wrong could someone help?

Try the use of java AWT:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
And code:
// TIFF image file read
BufferedImage tiffImage = ImageIO.read(new File("tiff-image.tiff"));
// Prepare the image before writing - with same dimensions
BufferedImage jpegImage = new BufferedImage(
tiffImage.getWidth(),
tiffImage.getHeight(),
BufferedImage.TYPE_INT_RGB);
// Draw image from original TIFF to the new JPEG image
jpegImage.createGraphics().drawImage(tiffImage, 0, 0, Color.WHITE, null);
// Write the image as JPEG to disk
ImageIO.write(jpegImage, "jpg", new File("jpeg-image.jpg"));

Related

Convert svg image to png in java by servlet

Here, I am trying to send a SVG image to local server and in output I want to download that image in PNG / JPEG format.
While I have found some solutions but those are done by BATIK libraries, but in my Eclipse BATIK libraries are not supported , so I can't use the batik libraries.
Use batik library. Below is the code.
import java.io.*;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import java.nio.file.Paths;
import java.nio.file.Path;
public class svg2png {
public static void main(String[] args) throws Exception {
//Step -1: We read the input SVG document into Transcoder Input
//We use Java NIO for this purpose
String svg_URI_input = Paths.get("chessboard.svg").toUri().toURL().toString();
TranscoderInput input_svg_image = new TranscoderInput(svg_URI_input);
//Step-2: Define OutputStream to PNG Image and attach to TranscoderOutput
OutputStream png_ostream = new FileOutputStream("chessboard.png");
TranscoderOutput output_png_image = new TranscoderOutput(png_ostream);
// Step-3: Create PNGTranscoder and define hints if required
PNGTranscoder my_converter = new PNGTranscoder();
// Step-4: Convert and Write output
my_converter.transcode(input_svg_image, output_png_image);
// Step 5- close / flush Output Stream
png_ostream.flush();
png_ostream.close();
}
}
Hope it will help you.
Refer this: http://thinktibits.blogspot.com/2012/12/Batik-Convert-SVG-PNG-Java-Program-Example.html
You can also convert svg to png format without the use of Batik Transcoder.
BufferedImage input_image = null;
input_image = ImageIO.read(new File("Convert_to_PNG.svg")); //read svginto input_image object
File outputfile = new File("imageio_png_output.png"); //create new outputfile object
ImageIO.write(input_image, "PNG", outputfile);
By simply using the ImageIO library. Hope this will help!

Icon from a .lnk file to javafx Image

I'm am trying to get the Icon from a .lnk file, put it into a javafx Image and then save it as a .png file (to ensure it's working).
My current code compiles but does not work:
import java.io.*;
import java.util.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javafx.embed.swing.SwingFXUtils;
import java.awt.image.BufferedImage;
import java.awt.Graphics;
import javafx.scene.image.Image;
import javax.imageio.ImageIO;
class Iconic {
public static void main(String[] args) throws IOException{
File origin = new File("C:\\Users\\00001\\OneDrive.lnk");
Icon icn = FileSystemView.getFileSystemView().getSystemIcon(origin);
ImageIcon ico = ((ImageIcon) icn);
BufferedImage bi = new BufferedImage(
ico.getIconWidth(),
ico.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
ico.paintIcon(null,g,0,0);
g.dispose();
Image img = SwingFXUtils.toFXImage(bi,null);
File output = new File("C:\\Users\\00001\\");
BufferedImage bim = SwingFXUtils.fromFXImage(img,null);
ImageIO.write(bim,".png",output);
}
}
You are almost there, however, there are two issues in your code. Both are related to the ImageIO.write(...) method.
From the API doc of ImageIO.write(RenderedImage, String, File):
Writes an image using an arbitrary ImageWriter that supports the given format to a File. If there is already a File present, its contents are discarded.
Parameters:
im - a RenderedImage to be written.
formatName - a String containg the informal name of the format.
output - a File to be written to.
The second parameter is the format name, not the file extension. So, the second argument should be "PNG", not ".png". Because ImageIO does not find any plugins that can write ".png" format, the write(...) invocation will just silently return false. I recommend always checking the return value of ImageIO.write(...).
The third parameter is the destination file to write. The path of this file has to point to a file, however yours point only to a directory. If you fix only the format name above, you'll see that most likely you get an IOException.
So, a fixed version of your writing code would like like:
File output = new File(origin.getParentFile(), origin.getName().replace(".lnk", ".png"));
if (!ImageIO.write(bi, "PNG", output)) {
System.err.println("Could not write icon");
}
I deliberately left the conversion from FX Image out. You should be able to write bi directly, without conversion to and from FX Image(unless, of course, you manipulate the image in FX).

Extract image's width, height, color and type from byte array

I have an image in the format of byte[] array in my Java code. I want the following information extracted from that array. How can I do it as fast as possible.
Width
Height
Color (black & white, color or transparent? If color, what is the main color?)
Type (Is the image PNG, GIF, JPEG, etc.)
Use ImageIO to read as buffered image and then get relevant things which you want. See java doc at http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html.
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
public class Test {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// assuming that picture is your byte array
byte[] picture = new byte[30];
InputStream in = new ByteArrayInputStream(picture);
BufferedImage buf = ImageIO.read(in);
ColorModel model = buf.getColorModel();
int height = buf.getHeight();
}
}
To get the image type from the byte array, you can do something like:
byte[] picture = new byte[30];
ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(picture));
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
while (readers.hasNext()) {
ImageReader read = readers.next();
System.out.println("format name = " + read.getFormatName());
}
Here is the output I have for different files:
format name = png
format name = JPEG
format name = gif
It was inspired from:
Convert Byte Array to image in Java - without knowing the type

Storing DPI and Paper Size information in a JPEG with Java

I have the following code:
ImageIO.write(originalImage, OUTPUT_TYPE, resultOutput);
This is an invocation of the following javax.imageio.ImageIO method:
public static boolean write(RenderedImage im,
String formatName,
File output)
throws IOException
This turns an original BMP image into a JGP output. Is it possible to also store DPI and Paper Size information in the JPEG to aid in printing operations?
I found this post for setting DPI on PNG Files. It pointed out that you should use 'metadata.mergeTree' to properly save your metadata.
With that in mind, here is some working groovy code that takes a BMP file and creates a JPG file at arbitrary DPI:
import java.awt.image.BufferedImage
import java.io.File
import java.util.Hashtable
import java.util.Map
import javax.imageio.*
import javax.imageio.stream.*
import javax.imageio.metadata.*
import javax.imageio.plugins.jpeg.*
import org.w3c.dom.*
File sourceFile = new File("sample.bmp")
File destinationFile = new File("sample.jpg")
dpi = 100
BufferedImage sourceImage = ImageIO.read(sourceFile)
ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpeg").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(destinationFile);
imageWriter.setOutput(ios);
def jpegParams = imageWriter.getDefaultWriteParam();
IIOMetadata data = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(sourceImage), jpegParams);
Element tree = (Element)data.getAsTree("javax_imageio_jpeg_image_1.0");
Element jfif = (Element)tree.getElementsByTagName("app0JFIF").item(0);
jfif.setAttribute("Xdensity", Integer.toString(dpi));
jfif.setAttribute("Ydensity", Integer.toString(dpi));
jfif.setAttribute("resUnits", "1"); // density is dots per inch
data.mergeTree("javax_imageio_jpeg_image_1.0",tree)
// Write and clean up
imageWriter.write(data, new IIOImage(sourceImage, null, data), jpegParams);
ios.close();
imageWriter.dispose();
Worked fine for me in that OSX's Preview app and Gimp both reported that the resulting image was 100 DPI. As to Paper Size...I imagine this is directly determined by DPI? I couldn't find any JPEG property that would set that particular value.
You may consider using Commons Sanselan, instead of ImageIO for this task.
See http://commons.apache.org/sanselan/whysanselan.html for more info.

Image transcoding (JPEG to PNG) with Java

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

Categories