Java中圖片的常用操作代碼總結

前言

本文主要使用Java對圖片各種操作進行處理。

一、獲取系統支持圖片格式

代碼:

System.out.println(Arrays.asList(ImageIO.getReaderFormatNames()));
System.out.println(Arrays.asList(ImageIO.getReaderFileSuffixes()));
System.out.println(Arrays.asList(ImageIO.getReaderMIMETypes()));

String[] writerFormatName = ImageIO.getWriterFormatNames();
String[] writerSuffixName = ImageIO.getWriterFileSuffixes();
String[] writerMIMEType = ImageIO.getWriterMIMETypes();

輸出:

[JPG, jpg, tiff, pcx, PCX, bmp, BMP, gif, GIF, WBMP, png, PNG, raw, RAW, JPEG, pnm, PNM, tif, TIF, TIFF, wbmp, jpeg]
[, jpg, tiff, pcx, bmp, gif, png, ppm, tif, pgm, wbmp, jpeg, pbm]
[, image/vnd.wap.wbmp, image/png, image/jpeg, image/x-portable-graymap, image/pcx, image/bmp, image/gif, image/x-windows-pcx, image/x-windows-bmp, image/x-pc-paintbrush, image/x-pcx, image/x-bmp, image/x-png, image/x-portable-bitmap, image/x-portable-pixmap, image/tiff, image/x-portable-anymap]

二、生成自定義圖片

代碼:

@SneakyThrows
public static void main(String[] args) {
    BufferedImage bufferedImage = new BufferedImage(400, 400, BufferedImage.TYPE_INT_BGR);
    Graphics g = bufferedImage.getGraphics();
    try {
        g.fillRect(20, 40, 400, 400);
        g.setColor(new Color(120, 120, 120));
        g.setFont(new Font("隸書", Font.BOLD, 28));
        g.drawString("自定義圖片", 200, 200);
        ImageIO.write(bufferedImage, "jpg", new File("D:/test.jpg"));
    } finally {
        g.dispose();//釋放畫筆
    }
}

輸出:

三、獲取圖片格式

代碼:

 public static String getImageFormatName(File file) throws IOException {
     String formatName = null;
     ImageInputStream iis = ImageIO.createImageInputStream(file);
     Iterator<ImageReader> imageReader = ImageIO.getImageReaders(iis);
     if (imageReader.hasNext()) {
         ImageReader reader = imageReader.next();
         formatName = reader.getFormatName();
     }
     return formatName;
 }

四、圖片裁剪

public static String cutImage(String sourcePath, String targetPath, int x, int y, int width, int height) throws IOException {
        File file = new File(sourcePath);
        if (!file.exists()) {
            throw new IOException("not found the image:" + sourcePath);
        }
        if (null == targetPath || targetPath.isEmpty()) {
            targetPath = sourcePath;
        }

        String formatName = getImageFormatName(file);
        if (null == formatName) {
            return targetPath;
        }
        formatName = formatName.toLowerCase();

        // 防止圖片後綴與圖片本身類型不一致的情況
        String pathPrefix = getPathWithoutSuffix(targetPath);
        targetPath = pathPrefix + formatName;

        // GIF需要特殊處理
        if (IMAGE_FORMAT.GIF.getValue() == formatName) {
            GifDecoder decoder = new GifDecoder();
            int status = decoder.read(sourcePath);
            if (status != GifDecoder.STATUS_OK) {
                throw new IOException("read image " + sourcePath + " error!");
            }

            AnimatedGifEncoder encoder = new AnimatedGifEncoder();
            encoder.start(targetPath);
            encoder.setRepeat(decoder.getLoopCount());
            for (int i = 0; i < decoder.getFrameCount(); i++) {
                encoder.setDelay(decoder.getDelay(i));
                BufferedImage childImage = decoder.getFrame(i);
                BufferedImage image = childImage.getSubimage(x, y, width, height);
                encoder.addFrame(image);
            }
            encoder.finish();
        } else {
            BufferedImage image = ImageIO.read(file);
            image = image.getSubimage(x, y, width, height);
            ImageIO.write(image, formatName, new File(targetPath));
        }
        return targetPath;
    }

五、圖片壓縮

 public static String zoom(String sourcePath, String targetPath, int width, int height) throws IOException {
        File file = new File(sourcePath);
        if (!file.exists()) {
            throw new IOException("not found the image :" + sourcePath);
        }
        if (null == targetPath || targetPath.isEmpty()) {
            targetPath = sourcePath;
        }
        String formatName = getImageFormatName(file);
        if (null == formatName) {
            return targetPath;
        }
        formatName = formatName.toLowerCase();
        String pathPrefix = getPathWithoutSuffix(targetPath);
        targetPath = pathPrefix + formatName;

        // GIF處理
        if (IMAGE_FORMAT.GIF.getValue() == formatName) {
            GifDecoder decoder = new GifDecoder();
            int status = decoder.read(sourcePath);
            if (status != GifDecoder.STATUS_OK) {
                throw new IOException("read image " + sourcePath + " error!");
            }
            AnimatedGifEncoder encoder = new AnimatedGifEncoder();
            encoder.start(targetPath);
            encoder.setRepeat(decoder.getLoopCount());
            for (int i = 0; i < decoder.getFrameCount(); i++) {
                encoder.setDelay(decoder.getDelay(i));
                BufferedImage image = zoom(decoder.getFrame(i), width, height);
                encoder.addFrame(image);
            }
            encoder.finish();
        } else {
            BufferedImage image = ImageIO.read(file);
            BufferedImage zoomImage = zoom(image, width, height);
            ImageIO.write(zoomImage, formatName, new File(targetPath));
        }
        return targetPath;
    }

六、圖片水印

  private static void waterMark(Image srcImg, String path) throws IOException {
        int srcImgWidth = srcImg.getWidth(null);
        int srcImgHeight = srcImg.getHeight(null);
/*
        //網絡圖片
        URL url = new URL("url");
        //將URL對象輸入流轉化為圖片對象 (url.openStream()方法,獲得一個輸入流)
        Image srcImg = ImageIO.read(url.openStream());
        //獲取圖片的寬
        int srcImgWidth = srcImg.getWidth(null);
        //獲取圖片的高
        int srcImgHeight = srcImg.getHeight(null);
        System.out.println("圖片的寬:"+srcImgWidth);
        System.out.println("圖片的高:"+srcImgHeight);
*/
        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        // 加水印
        //創建畫筆
        Graphics2D g = bufImg.createGraphics();
        //繪制原始圖片
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
/*
        //文字水印
        //根據圖片的背景設置水印顏色
        g.setColor(new Color(255, 255, 255, 128));
        //設置字體  畫筆字體樣式為微軟雅黑,加粗,文字大小為60pt
        g.setFont(new Font("微軟雅黑", Font.BOLD, 60));
        String waterMarkContent = "自定義水印";
        //設置水印的坐標(為原圖片中間位置)
        int x = srcImgWidth / 2;
        int y = srcImgHeight / 2;
        //畫出水印 第一個參數是水印內容,第二個參數是x軸坐標,第三個參數是y軸坐標
        g.drawString(waterMarkContent, x, y);
        g.dispose();*/

        //圖片水印
        // 水印文件
        String waterMarkImage = "D:/print.jpg";
        Image srcWaterMark = ImageIO.read(new File(waterMarkImage));
        //獲取水印圖片的寬度
        int widthWaterMark = srcWaterMark.getWidth(null);
        //獲取水印圖片的高度
        int heightWaterMark = srcWaterMark.getHeight(null);
        //設置 alpha 透明度:alpha 必須是范圍 [0.0, 1.0] 之內(包含邊界值)的一個浮點數字
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.9f));
        //繪制水印圖片
        g.drawImage(srcWaterMark, (srcImgWidth - widthWaterMark) / 10,
                (srcImgHeight - heightWaterMark) / 10, widthWaterMark, heightWaterMark, null);
        // 水印文件結束
        g.dispose();

        //文件輸出地址
        String tarImgPath = path;
        // 輸出圖片
        FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
        ImageIO.write(bufImg, "png", outImgStream);
        outImgStream.flush();
        outImgStream.close();
    }

七、Thumbnails工具類

通過以上對圖片的各種操作,還是需要對流進行轉化,那是不是已經有成型的工具類瞭呢?對,Thumbnails工具類就能對以上各種情況處理。

主要有以下功能處理:

  • 旋轉
  • 水印
  • 裁剪
  • 指定大小進行縮放
  • 按照比例進行縮放
  • 不按照比例,指定大小進行縮放
  • 轉化圖片格式
  • 輸出到OutputStream
  • 輸出到BufferedImage

代碼示例如下:

依賴

<dependency>
        <groupId>net.coobird</groupId>
        <artifactId>thumbnailator</artifactId>
        <version>0.4.17</version>
</dependency>

代碼

 @SneakyThrows
    public static void main(String[] args) {
        //指定大小進行縮放
        Thumbnails.of("D:/test.jpg").size(100, 100).toFile("D:/test.jpg.jpg");

        //按照比例進行縮放
        // scale 圖片的壓縮比例 值在0-1之間,1f就是原圖,0.5就是原圖的一半大小
        // outputQuality 圖片壓縮的質量 值在0-1 之間,越接近1質量越好,越接近0 質量越差
        Thumbnails.of("D:/test.jpg").scale(0.75f).outputQuality(0.8f).toFile("D:/test.jpg");

        //不按照比例,指定大小進行縮放 100 keepAspectRatio(false) 默認是按照比例縮放的
        Thumbnails.of("D:/test.jpg").size(100, 100).keepAspectRatio(false).toFile("D:/test.jpg");

        //旋轉  rotate(角度),正數:順時針 負數:逆時針
        Thumbnails.of("D:/test.jpg").size(1024, 1024).rotate(90).toFile("C:/image+90.jpg");

        //水印 watermark(位置,水印圖,透明度)
        Thumbnails.of("D:/test.jpg").size(1024, 1024)
                .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("水印地址")), 0.5f)
                .outputQuality(0.4f).toFile("輸出地址");

        //裁剪
        Thumbnails.of("D:/test.jpg").sourceRegion(Positions.CENTER, 400, 400).size(200, 200).keepAspectRatio(false)
                .toFile("輸出地址");

        //轉化圖片格式
        Thumbnails.of("D:/test.jpg").size(666, 666).outputFormat("png").toFile("D:/test.png");

        // 輸出到OutputStream
        OutputStream os = new FileOutputStream("D:/test.jpg");
        Thumbnails.of("test.jpg").size(666, 666).toOutputStream(os);

        //輸出到BufferedImage
        BufferedImage thumbnail = Thumbnails.of("D:/test.jpg").size(666, 666).asBufferedImage();
        ImageIO.write(thumbnail, "jpg", new File("test.jpg"));
    }

到此這篇關於Java中圖片的常用操作代碼總結的文章就介紹到這瞭,更多相關Java圖片操作內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: