Java save bufferedimage as file

Write an image to file – Java BufferedImage ImageIO

In the following tutorial we demonstrate how to write an image to a file. We can write and convert different images. In this example we read a JPG file and convert the image to a PNG , GIF and BMP file.

How to Write an Image in Java

This example shows how to write an image in java. We write the file in multiple formats.

  • JPEG – Joint Photographic Experts Group.
  • PNG – Portable Network Graphics.
  • GIF – Graphic Interchange Format.
  • BMP – Windows Bitmap Image.
  • TIFF – Tagged Image File Format.
package com.memorynotfound.image; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; public class WriteImageExample < public static void main(String. args) throws IOException < // read image from folder URL input = new URL("https://memorynotfound.com/wp-content/uploads/java-duke-to-jpg.jpg"); BufferedImage image = ImageIO.read(input); ImageIO.write(image, "png", new File("/tmp/duke.png")); ImageIO.write(image, "gif", new File("/tmp/duke.gif")); ImageIO.write(image, "bmp", new File("/tmp/duke.bmp")); ImageIO.write(image, "tiff", new File("/tmp/duke.tiff")); >>

Converted Images

To demonstrate the result, we added the following table.

duke.jpg (original) duke.png duke.gif duke.bmp
Size: 12KB Size: 46KB Size: 12KB Size: 423KB

References

Источник

Writing/Saving an Image

This lesson started with an explanation for using the javax.imageio package, to load images from an external image format into the internal BufferedImage format used by Java 2D. Then it explains how to use the Graphics.drawImage() to draw that image, with optional filtering.

The final stage is saving a BufferedImage object into an external image format. This may be an image that was originally loaded by the Image I/O class from an external image format and perhaps modified using the Java 2D APIs, or it may be one that was created by Java 2D.

The Image I/O class provides a simple way to save images in a variety of image formats in the following example:

static boolean ImageIO.write(RenderedImage im, String formatName, File output) throws IOException

The formatName parameter selects the image format in which to save the BufferedImage .

The ImageIO.write method calls the code that implements PNG writing a “PNG writer plug-in”. The term plug-in is used since Image I/O is extensible and can support a wide range of formats.

But the following standard image format plugins : JPEG, PNG, GIF, BMP and WBMP are always be present.

Each image format has its advantages and disadvantages:

Читайте также:  Определите сумму всех трехзначных натуральных чисел python
Format Plus Minus
GIF Supports animation, and transparent pixels Supports only 256 colors and no translucency
PNG Better alternative than GIF or JPG for high colour lossless images, supports translucency Doesn’t support animation
JPG Great for photographic images Loss of compression, not good for text, screenshots, or any application where the original image must be preserved exactly

For most applications it is sufficient to use one of these standard plugins. They have the advantage of being readily available. The Image I/O class provides a way to plug in support for additional formats which can be used, and many such plug-ins exist. If you are interested in what file formats are available to load or save in your system, you may use the getReaderFormatNames and getWriterFormatNames methods of the ImageIO class. These methods return an array of strings listing all of the formats supported in this JRE.

String writerNames[] = ImageIO.getWriterFormatNames();

The returned array of names will include any additional plug-ins that are installed and any of these names may be used as a format name to select an image writer. The following code example is a simple version of a complete image edit/touch up program which uses a revised version of the ImageDrawingApplet.java sample program which can be used as follows :

  • An image is first loaded via Image I/O
  • The user selects a filter from the drop down list and a new updated image is drawn
  • The user selects a save format from the drop down list
  • Next a file chooser appears and the user selects where to save the image
  • The modified image can now be viewed by other desktop applications

The complete code of this example is represented in SaveImage.java .

In this lesson you have learned just the basics of Image I/O , which provides extensive support for writing images, including working directly with an ImageWriter plug-in to achieve finer control over the encoding process. ImageIO can write multiple images, image metadata, and determine quality vs. size tradeoffs. For more information see Java Image I/O API Guide.

Источник

Saving a BufferedImage as a PNG, JPEG etc

Having created a BufferedImage to represent a graphic image in Java and set pixels on that image as appropriate, a common next step is to want to save that image to disk in a common image format such as JPEG, PNG etc.

Saving a BufferedImage as a PNG

You can easily save a BufferedImage in one of these formats thanks to the static utility method ImageIO.write(). To save a BufferedImage as a PNG file, the following will suffice:

BufferedImage img = . File f = new File("MyFile.png"); ImageIO.write(img, "PNG", f); 

Saving a BufferedImage as a JPEG

The procedure for writing an image file as a JPEG is similar:

BufferedImage img = . File f = new File("MyFile.jpg"); ImageIO.write(img, "JPEG", f); 

(You can also specify «JPG» instead of «JPEG».)

Which format should I use: PNG or JPEG?

In general, the choice depends on (a) whether you need your image to include transparency information, and (b) whether or not it matters if pixels in the saved image differ slightly from the original in order to give greater compression.

  • JPEG is a format primarily designed for photographs and similar images, where preservation of the precise details of sharp outlines is not crucial. It is a so-called lossy compression algorithm: small detail, usually imperceptible for the purposes of viewing a photograph, is lost, but with the benefit of smaller image files. JPEG does not support transparency, so if your BufferedImage includes transparency, this information will be lost when you save it to a JPEG file.
  • The PNG format is a lossless format: precise details of each individual pixel will be retained, at the expense of a larger file. (The file is still compressed, however.) It also supports transparency. The PNG format is more suited to cases where either (a) transparency is needed, or (b) you are dealing with an image that isn’t a ‘normal photograph’ and where precise details of outlines of shapes need to be retained. For example, it is well suited to cartoon or technical drawings, scanned text etc.
Читайте также:  Can raspberry pi run python

Saving a BufferedImage in other formats

A couple of other formats are supported by the JDK as standard. You can save a BufferedImage as a GIF by specifying «GIF» as the format name to ImageIO.write(). Note that this will create a 256-colour indexed image. In other words, if your image contains more than 256 individual colours, then its quality will be degraded as each colour other than the 256 most common will be mapped to its closest neighbour of the most common 256. Due to this limitation, along with the fact that PNG offers a patent-free alternative to GIF, it is recommended only to use the GIF format when you have no alternative.

The BMP and WBMP formats are also supported as standard. The BMP format is lossless but typically results in larger files than other formats.

Error handling

As you might expect, ImageIO.write() will throw an IOException should an I/O error occur while writing the image. A quirk of this method, however, is that there are some types of error that do not actually throw an exception. This can occur if:

  • you request an unsupported image file type;
  • the plugin that deals with saving in the particular file type in question encounters some internal error.

In these latter cases, ImageIO.write() may instead return a value of false (instead of the usual value of true which it is common to ignore) to indicate failure. So if you are being ultra-careful, it is safer to do the following «just in case»:

BufferedImage img = . File f = new File(«MyFile.jpg»); if (!ImageIO.write(img, «JPEG», f))

This won’t solve the underlying problem, but it will prevent your program ‘failing silently’ at some point in the future and wasting your time with a lot of head-scratching trying to figure out what went wrong.

Читайте также:  Kafka python hello world

Источник

Write an image to file – Java BufferedImage ImageIO

In the following tutorial we demonstrate how to write an image to a file. We can write and convert different images. In this example we read a JPG file and convert the image to a PNG , GIF and BMP file.

How to Write an Image in Java

This example shows how to write an image in java. We write the file in multiple formats.

  • JPEG – Joint Photographic Experts Group.
  • PNG – Portable Network Graphics.
  • GIF – Graphic Interchange Format.
  • BMP – Windows Bitmap Image.
  • TIFF – Tagged Image File Format.
package com.memorynotfound.image; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; public class WriteImageExample < public static void main(String. args) throws IOException < // read image from folder URL input = new URL("https://memorynotfound.com/wp-content/uploads/java-duke-to-jpg.jpg"); BufferedImage image = ImageIO.read(input); ImageIO.write(image, "png", new File("/tmp/duke.png")); ImageIO.write(image, "gif", new File("/tmp/duke.gif")); ImageIO.write(image, "bmp", new File("/tmp/duke.bmp")); ImageIO.write(image, "tiff", new File("/tmp/duke.tiff")); >>

Converted Images

To demonstrate the result, we added the following table.

duke.jpg (original) duke.png duke.gif duke.bmp
Size: 12KB Size: 46KB Size: 12KB Size: 423KB

References

Источник

How to read and write an image in Java

In Java, we can use the javax.imageio.ImageIO class to read and write an image.

1. Read an image

Read an image from a file.

 BufferedImage image = ImageIO.read(new File("c:\\test\\image.png")); 

Read an image from an URL.

 BufferedImage image = ImageIO.read(new URL("https://example.com/image.png")); 

2. Write or save an image

Write or save an image in different image formats.

 ImageIO.write(bufferedImage , "jpg", new File("c:\\test\\image.jpg")); ImageIO.write(bufferedImage , "gif", new File("c:\\test\\image.gif")); ImageIO.write(bufferedImage , "png", new File("c:\\test\\image.png")); 

Below code snippet list out all the supported formats.

 String writerNames[] = ImageIO.getWriterFormatNames(); Arrays.stream(writerNames).forEach(System.out::println); 
 PG jpg tiff bmp BMP gif GIF WBMP png PNG JPEG tif TIF TIFF wbmp jpeg 

3. Read, resize and save an image.

A full Java example of using ImageIO to read an image from an URL (Google logo), resize it to 300×150 and save it into a file.

 package com.mkyong.io.image; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; public class ReadWriteImage < // Google logo url private static final String GOOGLE_LOGO = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"; public static void main(String[] args) < try < URL url = new URL(GOOGLE_LOGO); // read an image from url BufferedImage image = ImageIO.read(url); // resize image to 300x150 Image scaledImage = image.getScaledInstance(300, 150, Image.SCALE_DEFAULT); // save the resize image aka thumbnail ImageIO.write( convertToBufferedImage(scaledImage), "png", new File("C:\\test\\google.png")); >catch (MalformedURLException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >System.out.println("Done"); > // convert Image to BufferedImage public static BufferedImage convertToBufferedImage(Image img) < if (img instanceof BufferedImage) < return (BufferedImage) img; >// Create a buffered image with transparency BufferedImage bi = new BufferedImage( img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D graphics2D = bi.createGraphics(); graphics2D.drawImage(img, 0, 0, null); graphics2D.dispose(); return bi; > > 

The downloaded image is resized to 300×150.

Источник

Оцените статью