當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java PNG Images轉JPEG用法及代碼示例


PNG 和 JPG 格式用於圖像插圖。這兩種格式都用於提供與某些類型圖像的良好兼容性,例如 PNG 更適合線條圖和圖標圖形,而 JPG 更適合照片。然而,兩者在媒體和圖片的使用和存儲方麵可以相互轉換。

在Java中,write()方法用於將圖像從gif類型格式轉換為jpg,使用類ImageIO提供的靜態方法write()javax.imageio包。以下實用程序類實現了一個靜態方法,稱為converImg(),它將輸入和輸出圖像路徑作為參數並格式化輸出圖像。

用法:

boolean write(RenderedImage image, String formatName, OutputStream output)

參數:write()方法接受3個參數,即圖像、格式名稱和輸出。

  1. Image: 輸入圖像作為RenderedImage接口的子類,例如BufferedImage。要從輸入圖像文件中獲取BufferedImage對象,我們可以使用read(Java.io.InputStream)這也是由 ImageIO 類提供的。
  2. formatName: 指定輸出圖像的格式類型。
  3. output 指定一個Java.io.OutputStream輸出圖像將寫入其中。

返回類型:布爾值,如果可以找到 ImageWriter 並成功執行轉換,則返回 true,否則返回 false。

異常:它會拋出IO異常如果執行過程中出現錯誤。稍後將在實現部分中展示。

執行:

Note: For input and output images path, Input and input images been passed are present on the desktop of the machine

  • Input image with name “demoImage.png”
  • Output Image with name “demoImage.jpeg”

Code is present at the directory mentioned below

  • /Users/mayanksolanki/Desktop/Job/Coding/GFG/Folder/

示例

Java


// Java Program to Convert PNG Image to JPEG Image
// Importing BufferedImage class from java.awt package
// to describe an image with accessible buffer of image
import java.awt.image.BufferedImage;
// Importing all input output classes
import java.io.*;
// Importing an interface
// to determine the setting of IIOParam object
import javax.imageio.ImageIO;
// Class 1
// helper class
class HelperClass {
    // Method
    // To convert image format
    public static boolean convertImg(String inputImgPath,
                                     String outputImgPath,
                                     String formatType)
        throws IOException
    {
        // Creating an object  of FileInputStream to read
        FileInputStream inputStream
            = new FileInputStream(inputImgPath);
        // Creating an object  of FileOutputStream to write
        FileOutputStream outputStream
            = new FileOutputStream(outputImgPath);
        // Reading the  input image from file
        BufferedImage inputImage
            = ImageIO.read(inputStream);
        // Writing to the output image in specified format
        boolean result = ImageIO.write(
            inputImage, formatType, outputStream);
        // Closing the streams in order to avoid read write
        // operations
        outputStream.close();
        inputStream.close();
        return result;
    }
}
// Class 2
// Main class
public class GFG {
    // Main class
    public static void main(String[] args)
    {
        // Here, the local directories from machine
        //  is passed as in strings
        // Creating a string to store the path of image
        // to be converted
        String inputImage
            = "/Users/mayanksolanki/Desktop/demoImage.png";
        // Creating a string to
        // store path of converted image
        String outputImage
            = "/Users/mayanksolanki/Desktop/demoImage.jpeg";
        // Creating another string that will be
        // store format of converted image
        // Simply creating  creating just to hold the format
        // type
        String formatType = "JPEG";
        // Try block to check for exceptions
        try {
            // result will store boolean value whether image
            // is converted successfully or not
            boolean result = HelperClass.convertImg(
                inputImage, outputImage, formatType);
            if (result) {
                // Display message when image is converted
                // successfully
                System.out.println(
                    "Image converted to jpeg successfully.");
            }
            else {
                // Display message when image is not
                // converted successfully
                System.out.println(
                    "Could not convert image.");
            }
        }
        // Catch block to handle the exceptions
        catch (IOException ex) {
            // Display message when exception is thrown
            System.out.println(
                "Error during converting image.");
            // Print the line number
            // where the exception occurred
            ex.printStackTrace();
        }
    }
}

輸出:

情況1:拋出錯誤時

情況2:編譯成功但運行時拋出異常(無法正常運行)

案例3:編譯成功並成功運行

Image converted to jpeg successfully.

執行後會顯示圖像已成功轉換為jpeg,我們可以在控製台上看到並在文件中創建了一個新的jpeg圖像



相關用法


注:本文由純淨天空篩選整理自sam_2200大神的英文原創作品 Java Program to Convert PNG Images to JPEG。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。