Home Java javaTutorial Detailed explanation of Java using ImageIO.writer to generate jpeg images from BufferedImage, summary and solutions to problems encountered

Detailed explanation of Java using ImageIO.writer to generate jpeg images from BufferedImage, summary and solutions to problems encountered

Mar 25, 2017 am 10:42 AM

This article mainly introduces the relevant information on the summary and solution of problems encountered in generating jpeg images from BufferedImage using ImageIO.writer in java. Friends in need can refer to the following

java Using ImageIO.writer to generate jpeg images from BufferedImage Summary and solutions to problems encountered when BufferedImage generates jpeg images

Generating jpeg images is a very, very simple thing. Many introductions on the Internet use com.sun.image.codec.jpeg directly. JPEGImageEncoder is implemented as follows:

  /**
   * 将原图压缩生成jpeg格式的数据
   * @param source
   * @return
   */
  public static byte[] wirteJPEGBytes(BufferedImage source){
    if(null==source)
      throw new NullPointerException();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    JPEGImageEncoder jencoder = JPEGCodec.createJPEGEncoder(output);
    JPEGEncodeParam param = jencoder.getDefaultJPEGEncodeParam(source);
    param.setQuality(0.75f, true);
    jencoder.setJPEGEncodeParam(param);
    try {
      jencoder.encode(source);
    } catch (ImageFormatException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return output.toByteArray();  
  }
Copy after login

JPEGImageEncoder is just sun’s jpeg encoding implementation. It is not a standard Java API. It is only supported in sun jvm, but will not be used on other jvm. support.

Also, although the above code can be executed normally on Java 1.6 and 1.7, if you use java 1.8, the above code will report an error:

Access restrictions: Due to The required library C:\Program Files\Java\jdk1.8.0_111\jre\lib\rt.jar has certain restrictions and therefore cannot access type JPEGImageEncoder

Detailed explanation of Java using ImageIO.writer to generate jpeg images from BufferedImage, summary and solutions to problems encountered

So this method has limitations.

It is not possible to take shortcuts. You still have to follow the Java specifications. The ImageIO class provides the ImageIO.writer method to generate images in the specified format. This is the formal implementation method. .

But there are also some considerations when using the ImageIO.writer method.

I originally wrote it like this, which is to simply call the ImageIO.writer method to generate jpeg data:

  /**
   * 将原图压缩生成jpeg格式的数据
   * @param source
   * @return
   * @see #wirteBytes(BufferedImage, String)
   */
  public static byte[] wirteJPEGBytes(BufferedImage source){
    return wirteBytes(source,"JPEG");
  }
  /**
   * 将原图压缩生成jpeg格式的数据
   * @param source
   * @return
   * @see #wirteBytes(BufferedImage, String)
   */
  public static byte[] wirteJPEGBytes(BufferedImage source){
    return wirteBytes(source,"JPEG");
  }
  /**
   * 将{@link BufferedImage}生成formatName指定格式的图像数据
   * @param source
   * @param formatName 图像格式名,图像格式名错误则抛出异常
   * @return
   */
  public static byte[] wirteBytes(BufferedImage source,String formatName){
    Assert.notNull(source, "source");
    Assert.notEmpty(formatName, "formatName");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {      
      if(!ImageIO.write(source, formatName.toLowerCase(), output))
        // 返回false则抛出异常
        throw new IllegalArgumentException(String.format("not found writer for '%s'",formatName));

    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return output.toByteArray();    
  }
Copy after login

It has no problem processing tens of thousands of image files. When I encounter one png image, ImageIO.write actually returned false and threw an exception.

The reason is that when the private method getWriter called by the ImageIO.wite method looks for a suitable ImageWriter, it is not only related to the formatName, but also to the input original image (specifically how it is related, because the logic The relationship is too complicated and has not been studied in depth), causing the getWriter method to not be able to find the corresponding ImageWriter.

Refer to other people’s writing methods on the Internet and change it to this, no problem:

  /**
   * 将{@link BufferedImage}生成formatName指定格式的图像数据
   * @param source
   * @param formatName 图像格式名,图像格式名错误则抛出异常
   * @return
   */
  public static byte[] wirteBytes(BufferedImage source,String formatName){
    Assert.notNull(source, "source");
    Assert.notEmpty(formatName, "formatName");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    BufferedImage newBufferedImage = new BufferedImage(source.getWidth(),
        source.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g = newBufferedImage.createGraphics();
    try {
      g.drawImage(source, 0, 0,null);
      if(!ImageIO.write(newBufferedImage, formatName, output))
        throw new IllegalArgumentException(String.format("not found writer for '%s'",formatName));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }finally{
      g.dispose();
    }
    return output.toByteArray();    
  }
Copy after login

The basic idea is to recreate a BufferedImage of the same size, and then use the Graphics.drawImage method to draw the original image Write a new BufferedImage object. Through this conversion, the differences between BufferedImage objects generated by different types of image formats are smoothed out, and then call ImageIO.write to ## the new ImageIO.write object. #Image processing There will be no problem.

Improvement

In my project, the image data is

searched from the Internet. Most of the image formats encountered are jpeg, but there are also a small number of png, bmp and other formats. For the vast majority of jpeg images, my initial method is effective, but the above method seems a bit redundant and wastes resources because it requires one more step. , so the above method has been improved. The basic principle is to first try to directly ImageIO.write to generate jpeg. If it fails, use the second method.

  /**
   * 将{@link BufferedImage}生成formatName指定格式的图像数据
   * @param source
   * @param formatName 图像格式名,图像格式名错误则抛出异常
   * @return
   */
  public static byte[] wirteBytes(BufferedImage source,String formatName){
    Assert.notNull(source, "source");
    Assert.notEmpty(formatName, "formatName");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    Graphics2D g = null;
    try {
      for(BufferedImage s=source;!ImageIO.write(s, formatName, output);){
        if(null!=g)
          throw new IllegalArgumentException(String.format("not found writer for '%s'",formatName));
        s = new BufferedImage(source.getWidth(),
            source.getHeight(), BufferedImage.TYPE_INT_RGB);
        g = s.createGraphics();
        g.drawImage(source, 0, 0,null);       
      }        
    } catch (IOException e) {
      throw new RuntimeException(e);
    } finally {
      if (null != g)
        g.dispose();
    }
    return output.toByteArray();    
  }
Copy after login

The above is the detailed content of Detailed explanation of Java using ImageIO.writer to generate jpeg images from BufferedImage, summary and solutions to problems encountered. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles