首页 > 编程语言 >Java图片剪裁功能实现

Java图片剪裁功能实现

时间:2023-09-14 14:39:00浏览次数:30  
标签:Java int image BufferedImage param return 剪裁 图片


目前一些社交型互联网应用都有一些上传图片(例如头像,照片等)对预览图进行剪裁的功能。前一段时间在工作也遇到这个问题,总结一下基本实现步骤及代码(包含图片放大,缩小,设置品质,对指定点区域剪裁功能),使用JPEG格式图片测试通过,其它格式图片尚未验证。

一、基本步骤:

1.将图片文件的InputStream转换为ImageReader,并从ImageReader中读取BufferedImage信息.

2.然后使用javax.image包以及Java image scaling开源项目对图片进行缩放.

3.使用java.awt.image类对java.awt.BufferedImage进行剪裁.

4.最后写入文件,如果是JPG图片可以设置图片品质(压缩比)即JPEGEncodeParam.setQuality.

二、程序相关:

/**
     * 剪裁图片.
     * 
     * @param file 要剪裁的图片
     * @param scale 放大缩小比率
     * @param cropX x轴起点坐标
     * @param cropY y轴起点坐标
     * @param targetWidth 目标图片的长
     * @param targetHeight 目标图片的宽
     */
    public static File crop(File file, Double scale, int cropX, int cropY, int targetWidth, int targetHeight) throws IOException {
        BufferedImage source;
        String format;
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            
            // 从InputStream中读取图片流信息
            ImageInputStream iis = ImageIO.createImageInputStream(is);
            Iterator iter = ImageIO.getImageReaders(iis);
            if (!iter.hasNext()) {
                return null;
            }
            ImageReader reader = (ImageReader) iter.next();
            ImageReadParam param = reader.getDefaultReadParam();
            reader.setInput(iis, true, true);
            try {
                source = reader.read(0, param);
                format = reader.getFormatName();
            } finally {
                reader.dispose();
                iis.close();
            }
        } finally {
            IOUtils.closeQuietly(is);
        }
        
        //调整放大缩小比率
        int width = Double.valueOf(scale * source.getWidth()).intValue();
        int height = Double.valueOf(scale * source.getHeight()).intValue();
        BufferedImage scaled = scale(source, width, height);
        
        //剪裁图片
        ImageFilter filter = new CropImageFilter(cropX, cropY, targetWidth, targetHeight);
        Image cropped = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(scaled.getSource(), filter));
        
        //渲染新图片
        BufferedImage image = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.drawImage(cropped, 0, 0, null);
        g.dispose();
        
        //写入文件
        return writeToTempFile(image, format);
    }

其中用到了Java image scaling开源工具,对图片进行缩放。

/**
     * 放大缩小图片到指定宽和高
     * 
     * @param image Image to scale
     * @param width Width of image
     * @param height Height of image
     * @return Scaled image file
     */
    public static BufferedImage scale(BufferedImage image, int width, int height) {
        ResampleOp resampleOp = new ResampleOp(width, height);
        resampleOp.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.Normal);
        return resampleOp.filter(image, null);
    }

最后写入临时文件:

/**
     * 将图片写入临时文件
     */
    public static File writeToTempFile(BufferedImage image, Format type) {
        if (Format.JPEG != type) {
            return writeToTempFileWithoutCompress(image, type);
        } else {
            try {
                return compress(image, JPG_DEFAULT_QUALITY);
            } catch (IOException e) {
                return writeToTempFileWithoutCompress(image, type);
            }
        }
    }

不是JPEG格式不压缩:

/**
     * 不压缩将图片写入文件
     */
    public static File writeToTempFileWithoutCompress(BufferedImage image, Format type) {
        File destination = generateTempFile(type);
        try {
            ImageIO.write(image, type.toString(), destination);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return destination;
    }

    /**
     * 压缩图片到指定的压缩比率
     */
    public static File compress(BufferedImage image, float quality) throws IOException {
        // Build param
        JPEGEncodeParam param = null;
        try {
            param = JPEGCodec.getDefaultJPEGEncodeParam(image);
            param.setQuality(quality, false);
        } catch (RuntimeException e) {
            // Ignore
            param = null;
        }
        
        // Build encoder
        File destination = generateTempFile(Format.JPEG);
        FileOutputStream os = null;
        try {
            os = FileUtils.openOutputStream(destination);
            JPEGImageEncoder encoder;
            if (param != null) {
                encoder = JPEGCodec.createJPEGEncoder(os, param);
            } else {
                encoder = JPEGCodec.createJPEGEncoder(os);
            }
            encoder.encode(image);
        } finally {
            IOUtils.closeQuietly(os);
        }
        return destination;
    }

其中还用到了Apache的commons-io工具集。

 

测试时发现设置0.9以上的压缩比后会使有些JPG图片的大小不减小反而比原图更大了,具体原因还不太清楚。

希望对看到的人有所帮助。

 

标签:Java,int,image,BufferedImage,param,return,剪裁,图片
From: https://blog.51cto.com/u_6978506/7470081

相关文章

  • Java动态代理详解
    不定期整理硬盘内源代码、笔记、总结等,同时发上来分享一下。今天再发一篇关于Java动态代理的总结(貌似ItEye一天最多发5篇Blog,再多只能放草稿箱了?)-----------------------------------------------------------Java动态代理详解说到动态代理,顾名思义就是动态的代理(真是废话)。关......
  • 设计模式回顾之一:单例模式(Java的4种实现)
    设计模式回顾系列文章:主要针对工作中常用常见的设计模式进行整理、总结,同时分享以供大家拍砖。------------------------------------------------作为一个程序员,我并不知道"茴"字有4种写法。但是,我知道单例有4种写法。单例模式目的:保证一个类仅有一个实例,并提供一个访问它的全局访......
  • 无涯教程-JavaScript - ISREF函数
    描述如果指定的值是参考,则ISREF函数返回逻辑值TRUE。否则返回FALSE。语法ISREF(value)争论Argument描述Required/OptionalvalueAreferencetoacell.RequiredNotes您可以在执行任何操作之前使用此功能测试单元格的内容。适用性Excel2007,Excel2010,Excel......
  • How to fix java.net.SocketException: Too many files open in tomcat
    NotmanyJavaprogrammersknowsthatsocketconnectionsaretreatedlikefilesandtheyusefiledescriptor,whichisalimitedresource.Differentoperatingsystemhasdifferentlimitsonnumberoffilehandlestheycanmanage.Oneof......
  • java/jsp清除jsp缓存
    InJava:HttpServletResponseresponse=(HttpServletResponse)rep;response.setDateHeader("Expires",-1);response.setHeader("Cache_Control","no-cache");response.setHeader("Pragma","no-ca......
  • Rules for good java.util.Timer use
    ManypeoplehaveprobablyusedTimerforsomequickone-offtimertaskswhereusingawholelibrarylikeQuartzdon’tmakesense.OnethingtobeawareofisthatTimer’sconstructorwillstartandspawnathread.Thisisarecipefor......
  • java 日期函数
    得到过去的时间:exampleone:privateDategetDateTime(){ Calendarcalendar=Calendar.getInstance(); calendar.set(2011,Calendar.DECEMBER,1,23,0,0); returncalendar.getTime();}exampletwo:String.valueOf(newDate().getTime()-2......
  • (转)HashMap出现 java.util.ConcurrentModificationException
    Iterator<Integer>keys=gradeMap.keySet().iterator();while(keys.hasNext()){Integeri=keys.next();if(!gradesIds.contains(i)){//keys.remove();gradeMap.remove(i);}......
  • go 语言比java的优势提升编程效率的利器
    示例示例Go语言比Java有如下优势:Go语言的编译速度更快,可以提高开发效率。Go语言使用编译器进行编译,而Java使用解释器进行编译,Go的编译速度更快。Go语言比Java有如下优势:1.Go语言的编译速度更快,可以提高开发效率。Go语言使用编译器进行编译,而Java使用解释器进行编译......
  • Java8 Optional用法和最佳实践
    介绍根据Oracle文档,Optional是一个容器对象,可能包含也可能不包含非空值。Java8中引入它是为了解决NullPointerException的问题。本质上,Optional是一个包装类,其中包含对其他对象的引用。在这种情况下,对象只是指向内存位置的指针,它也可以指向任何内容。另一种看待它的方式......