Java 服务端图片格式转换

public class ImageConverter {

 

    /**

     * Converts an image to another format

     *

     * @param inputImagePath Path of the source image

     * @param outputImagePath Path of the destination image

     * @param formatName the format to be converted to, one of: jpeg, png,

     * bmp, wbmp, and gif

     * @return true if successful, false otherwise

     * @throws IOException if errors occur during writing

     */

    public static boolean convertFormat(String inputImagePath,

            String outputImagePath, String formatName) throws IOException {

        FileInputStream inputStream = new FileInputStream(inputImagePath);

        FileOutputStream outputStream = new FileOutputStream(outputImagePath);

         

        // reads input image from file

        BufferedImage inputImage = ImageIO.read(inputStream);

         

        // writes to the output image in specified format

        boolean result = ImageIO.write(inputImage, formatName, outputStream);

         

        // needs to close the streams

        outputStream.close();

        inputStream.close();

         

        return result;

    }

    

    public static boolean convertFormat(FileInputStream inputStream,

    FileOutputStream outputStream, String formatName) throws IOException {

         

        // reads input image from file

        BufferedImage inputImage = ImageIO.read(inputStream);

         

        // writes to the output image in specified format

        boolean result = ImageIO.write(inputImage, formatName, outputStream);

         

        // needs to close the streams

        outputStream.close();

        inputStream.close();

         

        return result;

    }

    

    public static void main(String[] args) {

        String inputImage = "/Users/xxxxx/Downloads/a.png";

        String oututImage = "/Users/xxxxx/Downloads/a.jpg";

        String formatName = "JPG";

        try {

            boolean result = ImageConverter.convertFormat(inputImage,

                    oututImage, formatName);

            if (result) {

                System.out.println("Image converted successfully.");

            } else {

                System.out.println("Could not convert image.");

            }

        } catch (IOException ex) {

            System.out.println("Error during converting image.");

            ex.printStackTrace();

        }

}

}


转自:http://www.codejava.net/java-se/graphics/convert-image-formats

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值