文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java实现图片切割功能

2024-04-02 19:55

关注

本文实例为大家分享了Java实现图片切割功能的具体代码,供大家参考,具体内容如下

工具类

package com.xudaolong.Utils;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;



public class ImageCutterUtil {

    public enum IMAGE_FORMAT {
        BMP("bmp"),
        JPG("jpg"),
        WBMP("wbmp"),
        JPEG("jpeg"),
        PNG("png"),
        GIF("gif");

        private String value;

        IMAGE_FORMAT(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }


    
    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 BufferedImage[] readerImage(File file) throws IOException {
        BufferedImage sourceImage = ImageIO.read(file);
        BufferedImage[] images = null;
        ImageInputStream iis = ImageIO.createImageInputStream(file);
        Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
        if (imageReaders.hasNext()) {
            ImageReader reader = imageReaders.next();
            reader.setInput(iis);
            int imageNumber = reader.getNumImages(true);
            images = new BufferedImage[imageNumber];
            for (int i = 0; i < imageNumber; i++) {
                BufferedImage image = reader.read(i);
                if (sourceImage.getWidth() > image.getWidth() || sourceImage.getHeight() > image.getHeight()) {
                    image = zoom(image, sourceImage.getWidth(), sourceImage.getHeight());
                }
                images[i] = image;
            }
            reader.dispose();
            iis.close();
        }
        return images;
    }

    
    public static BufferedImage[] processImage(BufferedImage[] images, int x, int y, int width, int height) throws Exception {
        if (null == images) {
            return images;
        }
        BufferedImage[] oldImages = images;
        images = new BufferedImage[images.length];
        for (int i = 0; i < oldImages.length; i++) {
            BufferedImage image = oldImages[i];
            images[i] = image.getSubimage(x, y, width, height);
        }
        return images;
    }

    
    public static void writerImage(BufferedImage[] images, String formatName, File file) throws Exception {
        Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName(formatName);
        if (imageWriters.hasNext()) {
            ImageWriter writer = imageWriters.next();
            String fileName = file.getName();
            int index = fileName.lastIndexOf(".");
            if (index > 0) {
                fileName = fileName.substring(0, index + 1) + formatName;
            }
            String pathPrefix = getFilePrefixPath(file.getPath());
            File outFile = new File(pathPrefix + fileName);
            ImageOutputStream ios = ImageIO.createImageOutputStream(outFile);
            writer.setOutput(ios);

            if (writer.canWriteSequence()) {
                writer.prepareWriteSequence(null);
                for (int i = 0; i < images.length; i++) {
                    BufferedImage childImage = images[i];
                    IIOImage image = new IIOImage(childImage, null, null);
                    writer.writeToSequence(image, null);
                }
                writer.endWriteSequence();
            } else {
                for (int i = 0; i < images.length; i++) {
                    writer.write(images[i]);
                }
            }

            writer.dispose();
            ios.close();
        }
    }

    
    public static void cutImage(File sourceFile, File destFile, int x, int y, int width, int height) throws Exception {
        // 读取图片信息
        BufferedImage[] images = readerImage(sourceFile);
        // 处理图片
        images = processImage(images, x, y, width, height);
        // 获取文件后缀
        String formatName = getImageFormatName(sourceFile);

        destFile = new File(getPathWithoutSuffix(destFile.getPath()) + formatName);

        // 写入处理后的图片到文件
        writerImage(images, formatName, destFile);
    }


    
    public static void getOSSupportsStandardImageFormat() {
        String[] readerFormatName = ImageIO.getReaderFormatNames();
        String[] readerSuffixName = ImageIO.getReaderFileSuffixes();
        String[] readerMIMEType = ImageIO.getReaderMIMETypes();
        System.out.println("========================= OS supports reader ========================");
        System.out.println("OS supports reader format name :  " + Arrays.asList(readerFormatName));
        System.out.println("OS supports reader suffix name :  " + Arrays.asList(readerSuffixName));
        System.out.println("OS supports reader MIME type :  " + Arrays.asList(readerMIMEType));

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

        System.out.println("========================= OS supports writer ========================");
        System.out.println("OS supports writer format name :  " + Arrays.asList(writerFormatName));
        System.out.println("OS supports writer suffix name :  " + Arrays.asList(writerSuffixName));
        System.out.println("OS supports writer MIME type :  " + Arrays.asList(writerMIMEType));
    }

    
    private static BufferedImage zoom(BufferedImage sourceImage, int width, int height) {
        BufferedImage zoomImage = new BufferedImage(width, height, sourceImage.getType());
        Image image = sourceImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        Graphics gc = zoomImage.getGraphics();
        gc.setColor(Color.WHITE);
        gc.drawImage(image, 0, 0, null);
        return zoomImage;
    }

    
    public static String getFilePrefixPath(File file) throws IOException {
        String path = null;
        if (!file.exists()) {
            throw new IOException("not found the file !");
        }
        String fileName = file.getName();
        path = file.getPath().replace(fileName, "");
        return path;
    }

    
    public static String getFilePrefixPath(String path) throws Exception {
        if (null == path || path.isEmpty()) throw new Exception("文件路径为空!");
        int index = path.lastIndexOf(File.separator);
        if (index > 0) {
            path = path.substring(0, index + 1);
        }
        return path;
    }

    
    public static String getPathWithoutSuffix(String src) {
        String path = src;
        int index = path.lastIndexOf(".");
        if (index > 0) {
            path = path.substring(0, index + 1);
        }
        return path;
    }

    
    public static String getFileName(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IOException("not found the file !");
        }
        return file.getName();
    }


    
    public static void main(String[] args) throws Exception {
        // 获取系统支持的图片格式
//        ImageCutterUtil.getOSSupportsStandardImageFormat();

        try {
            // 起始坐标,剪切大小
            int x = 14;
            int y = 24;
            int width = 62;
            int height = 62;

            // 参考图像大小
            int clientWidth = 88;
            int clientHeight = 88;


            File file = new File("/Users/mac/IdeaProjects/QRdemo/resources/src/com/xudaolong/QR/TestQR/QR.jpg");


            BufferedImage image = ImageIO.read(file);

            double destWidth = image.getWidth();
            double destHeight = image.getHeight();

            if (destWidth < width || destHeight < height)
                throw new Exception("源图大小小于截取图片大小!");

            double widthRatio = destWidth / clientWidth;
            double heightRatio = destHeight / clientHeight;

            x = Double.valueOf(x * widthRatio).intValue();
            y = Double.valueOf(y * heightRatio).intValue();
            width = Double.valueOf(width * widthRatio).intValue();
            height = Double.valueOf(height * heightRatio).intValue();

            System.out.println("裁剪大小  x:" + x + ",y:" + y + ",width:" + width + ",height:" + height);

            String formatName = getImageFormatName(file);
            String pathSuffix = "." + formatName;
            String pathPrefix = getFilePrefixPath(file);
            String targetPath = pathPrefix + System.currentTimeMillis() + pathSuffix;

            File destFile = new File(targetPath);

            ImageCutterUtil.cutImage(file, destFile, x, y, width, height);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

单方面测试

public void cutQR(String sourcePath) {

        try {
            File file = new File(sourcePath);

            BufferedImage image = ImageIO.read(file);

            // 起始坐标,剪切大小
            int x = 14;
            int y = 25;
            int width = 62;
            int height = 62;
            // 参考图像大小
            int clientWidth = 88;
            int clientHeight = 88;

            double destWidth = image.getWidth();
            double destHeight = image.getHeight();

            if (destWidth < width || destHeight < height)
                throw new Exception("源图大小小于截取图片大小!");


            double widthRatio = destWidth / clientWidth;
            double heightRatio = destHeight / clientHeight;

            //修改一下单位
            x = Double.valueOf(x * widthRatio).intValue();
            y = Double.valueOf(y * heightRatio).intValue();
            width = Double.valueOf(width * widthRatio).intValue();
            height = Double.valueOf(height * heightRatio).intValue();

            System.out.println("裁剪大小  x:" + x + ",y:" + y + ",width:" + width + ",height:" + height);

            //获取指定的名字
//            String formatName = getImageFormatName(file);
//            String pathSuffix = "." + formatName;
//            String pathPrefix = getFilePrefixPath(file);
//            String targetPath = pathPrefix + System.currentTimeMillis() + pathSuffix;

            //最后一步进行裁剪到指定的名字

            File destFile = new File(sourcePath);

            ImageCutterUtil.cutImage(file, destFile, x, y, width, height);

        } catch (Exception e) {
            e.printStackTrace();
        }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯