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;


/**
 * 图像裁剪以及压缩处理工具类
 * <p>
 * 主要针对动态的GIF格式图片裁剪之后,只出现一帧动态效果的现象提供解决方案
 * <p>
 * 提供依赖三方包解决方案(针对GIF格式数据特征一一解析,进行编码解码操作)
 * 提供基于JDK Image I/O 的解决方案(JDK探索失败)
 */
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;
        }
    }


    /**
     * 获取图片格式
     *
     * @param file 图片文件
     * @return 图片格式
     */
    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;
    }

    /*********************** 基于JDK 解决方案     ********************************/

    /**
     * 读取图片
     *
     * @param file 图片文件
     * @return 图片数据
     * @throws IOException
     */
    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;
    }

    /**
     * 根据要求处理图片
     *
     * @param images 图片数组
     * @param x      横向起始位置
     * @param y      纵向起始位置
     * @param width  宽度
     * @param height 宽度
     * @return 处理后的图片数组
     * @throws Exception
     */
    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;
    }

    /**
     * 写入处理后的图片到file
     * <p>
     * 图片后缀根据图片格式生成
     *
     * @param images     处理后的图片数据
     * @param formatName 图片格式
     * @param file       写入文件对象
     * @throws Exception
     */
    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();
        }
    }

    /**
     * 剪切格式图片
     * <p>
     * 基于JDK Image I/O解决方案
     *
     * @param sourceFile 待剪切图片文件对象
     * @param destFile   裁剪后保存文件对象
     * @param x          剪切横向起始位置
     * @param y          剪切纵向起始位置
     * @param width      剪切宽度
     * @param height     剪切宽度
     * @throws Exception
     */
    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));
    }

    /**
     * 压缩图片
     *
     * @param sourceImage 待压缩图片
     * @param width       压缩图片高度
     * @param height      压缩图片宽度
     */
    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;
    }

    /**
     * 获取某个文件的前缀路径
     * <p>
     * 不包含文件名的路径
     *
     * @param file 当前文件对象
     * @return
     * @throws IOException
     */
    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;
    }

    /**
     * 获取某个文件的前缀路径
     * <p>
     * 不包含文件名的路径
     *
     * @param path 当前文件路径
     * @return 不包含文件名的路径
     * @throws Exception
     */
    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;
    }

    /**
     * 获取不包含后缀的文件路径
     *
     * @param src
     * @return
     */
    public static String getPathWithoutSuffix(String src) {
        String path = src;
        int index = path.lastIndexOf(".");
        if (index > 0) {
            path = path.substring(0, index + 1);
        }
        return path;
    }

    /**
     * 获取文件名
     *
     * @param filePath 文件路径
     * @return 文件名
     * @throws IOException
     */
    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();
    }


    /**
     * @param args
     * @throws Exception
     */
    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();
        }

    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: 要将图片转换为LaTeX格式,你可以使用一些开源的Java库和工具。 首先,你可以使用Java图像处理库,如Java Advanced Imaging (JAI)或OpenCV来加载和处理图像。这些库可以帮助你读取图像文件,并对其进行预处理,如调整大小、降噪、增强对比度等。这些步骤可以提高最终转换结果的质量。 接下来,你需要将处理后的图像转换为二进制图像,这可以通过将颜色图像转换为灰度图像来实现,或者使用阈值化技术来提取包含文本的二进制区域。你可以使用Java图像处理库来执行这些操作。 然后,你可以使用开源的OCR(Optical Character Recognition,光学字符识别)库,如Tesseract,来识别图像中的文本。这些库通常提供Java绑定,并具有很高的识别准确度。你可以将处理后的二进制图像传递给OCR库,然后获得识别结果。 最后,你可以将OCR识别的文本转换为LaTeX格式。你可以使用Java字符串处理功能来清理和格式化识别结果,并使用LaTeX命令和语法来表示文本、公式和其他特殊字符。 总结起来,要将图片转换为LaTeX格式,你需要使用Java图像处理库将图像加载、预处理和转换为二进制图像。然后,使用OCR库来识别图像中的文本,最后将识别结果转换为LaTeX格式。这个过程需要使用一些开源库和技术,但可以通过Java编程实现。 ### 回答2: Java可以通过使用开源库或API来将图片转换为LaTeX格式。以下是一种可能的方法: 首先,我们需要使用Java中的图像处理库(如Java图像处理库ImageJ)加载要转换的图片。这可以通过使用Java的文件读取和图像处理功能来实现。 然后,我们可以将加载的图像转换为灰度或黑白图像,以便更容易进行后续处理。这可以通过应用图像处理算法(如二值化)来实现。 接下来,我们可以使用Java字符识别库(如Tesseract OCR)识别图像中的字符。这可以通过将图像分割为小块并对每个块执行字符识别来实现。标准的LaTeX字符和符号可以在字符识别过程中进行比对,从而确定哪些字符在图像中呈现。 最后,我们可以将识别的字符转换为LaTeX代码,并以LaTeX文件的形式保存。在生成的LaTeX文件中,我们可以使用适当的排版和格式设置来确保图像在呈现为Latex时具有良好的质量和可读性。 需要注意的是,由于图像处理和字符识别都是复杂的任务,因此可能需要进行一些试验和调整,以选择合适的参数和算法来实现最佳的结果。 通过以上步骤,我们可以使用Java图片转换为LaTeX格式。这种方法可以帮助用户将手写的公式或图表转换为LaTeX代码,以便在科学出版物、学术论文或技术文档中使用。 ### 回答3: Java是一种广泛应用于软件开发的编程语言,而图片转化为LaTeX则是一种将图片转化为LaTeX代码的技术。LaTeX是一种排版系统,常用于科技文献的撰写。 在Java中,可以通过使用开源的库或者API来实现将图片转化为LaTeX的功能。首先,需要读入待转化的图片文件,可以使用Java提供的图片处理库,如javax.imageio包中的ImageIO类来读取图片。然后,可以使用图片处理库中的方法将图片转化为二进制数组或者像素数组。接下来,可以根据转化后的图像数据,将其转化为LaTeX代码。 具体的转化过程可以根据需求进行设计,一种常见的方式是将图片转化为矢量图形,然后通过解析矢量图形数据生成对应的LaTeX代码。这可以通过使用Java中的矢量图形处理库,如Apache Batik来实现。另一种方式是将图片转化为灰度图像或者二值图像,然后将每个像素点的信息转化为LaTeX代码中对应的文本字符。 在进行图片转化为LaTeX的过程中,可能需要考虑到一些细节,如字体,尺寸,对比度等问题。可以通过在转化过程中设置相关的参数来控制这些细节。另外,需要注意选择合适的LaTeX模板来确保转化后的LaTeX代码能够正确地排版出来。 总结来说,要实现将图片转化为LaTeX,可以利用Java图片处理库,将图片数据转化为LaTeX代码。具体的实现方式可以根据需求进行设计,常用的方法包括将图片转化为矢量图形或者灰度/二值图像,然后将相应的数据转化为LaTeX代码。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天瞳月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值