Java 切图

切图的代码如下:

package com.fnpac.gotop.helper.image;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

/**
 * Created by liuchunlong on 2018/1/13.
 * <p>
 * 图片处理工具类
 */
public class ImageUtils {

    /**
     * 图片剪裁
     *
     * @param x          距离左上角的x轴距离
     * @param y          距离左上角的y轴距离
     * @param width      宽度
     * @param height     高度
     * @param sourcePath 图片源
     * @param descpath   目标位置
     */
    public static void imageCut(int x, int y, int width, int height,
                                String sourcePath, String descpath) {
        FileInputStream fis = null;
        ImageInputStream iis = null;
        try {

            String fileSuffix = sourcePath.substring(sourcePath.lastIndexOf(".") + 1);
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(fileSuffix);
            ImageReader reader = it.next();

            fis = new FileInputStream(sourcePath);
            iis = ImageIO.createImageInputStream(fis);

            reader.setInput(iis, true);

            ImageReadParam param = reader.getDefaultReadParam();
            Rectangle rect = new Rectangle(x, y, width, height);
            param.setSourceRegion(rect);

            BufferedImage bi = reader.read(0, param);
            ImageIO.write(bi, fileSuffix, new File(descpath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                fis = null;
            }
            if (iis != null) {
                try {
                    iis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                iis = null;
            }
        }
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,404评论 25 708
  • 前言 很多圈友最近围在一圈讨论一个话题——切图。那什么是切图?切图对美术和程序有什么关系?怎么切图?切图有哪些方法...
    七景鸣阅读 11,968评论 3 17
  • 爱是深深的理解和接受。
    珺曦阅读 194评论 0 1
  • 淮竹听寒mio阅读 267评论 0 0
  • 我喜爱一切不彻底的事物 ——张定浩 我喜爱一切不彻底的事物。 细雨中的日光,春天的冷, 秋千摇碎大风...
    默契逍遥阅读 531评论 0 2