JAVA生成图片缩略图、JAVA截取图片局部内容

news2024/10/6 12:28:51

JAVA生成图片缩略图、JAVA截取图片局部内容

目前,google已经有了更好的处理JAVA图片的工具,请搜索:Thumbnailator

JAVA生成图片缩略图

package com.ares.image.test;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ares.slf4j.test.Slf4jUtil;

/**
 * <p>Title: ImageUtil </p>
 * <p>Description: 使用JDK原生态类生成图片缩略图和裁剪图片 </p>
 * <p>Email: icerainsoft@hotmail.com </p> 
 * @author Ares
 * @date 2014年10月28日 上午10:24:26
 */
public class ImageUtil {

    static {
        Slf4jUtil.buildSlf4jUtil().loadSlf4j();
    }
    private Logger log = LoggerFactory.getLogger(getClass());
    
    private static String DEFAULT_PREVFIX = "thumb_";
    private static Boolean DEFAULT_FORCE = false;
    
    /**
     * <p>Title: thumbnailImage</p>
     * <p>Description: 根据图片路径生成缩略图 </p>
     * @param imagePath    原图片路径
     * @param w            缩略图宽
     * @param h            缩略图高
     * @param prevfix    生成缩略图的前缀
     * @param force        是否强制按照宽高生成缩略图(如果为false,则生成最佳比例缩略图)
     */
    public void thumbnailImage(File imgFile, int w, int h, String prevfix, boolean force){
        if(imgFile.exists()){
            try {
                // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
                String types = Arrays.toString(ImageIO.getReaderFormatNames());
                String suffix = null;
                // 获取图片后缀
                if(imgFile.getName().indexOf(".") > -1) {
                    suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1);
                }// 类型和图片后缀全部小写,然后判断后缀是否合法
                if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0){
                    log.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types);
                    return ;
                }
                log.debug("target image's size, width:{}, height:{}.",w,h);
                Image img = ImageIO.read(imgFile);
                if(!force){
                    // 根据原图与要求的缩略图比例,找到最合适的缩略图比例
                    int width = img.getWidth(null);
                    int height = img.getHeight(null);
                    if((width*1.0)/w < (height*1.0)/h){
                        if(width > w){
                            h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0)));
                            log.debug("change image's height, width:{}, height:{}.",w,h);
                        }
                    } else {
                        if(height > h){
                            w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0)));
                            log.debug("change image's width, width:{}, height:{}.",w,h);
                        }
                    }
                }
                BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Graphics g = bi.getGraphics();
                g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
                g.dispose();
                String p = imgFile.getPath();
                // 将图片保存在原目录并加上前缀
                ImageIO.write(bi, suffix, new File(p.substring(0,p.lastIndexOf(File.separator)) + File.separator + prevfix +imgFile.getName()));
            } catch (IOException e) {
               log.error("generate thumbnail image failed.",e);
            }
        }else{
            log.warn("the image is not exist.");
        }
    }
    
    public void thumbnailImage(String imagePath, int w, int h, String prevfix, boolean force){
        File imgFile = new File(imagePath);
        thumbnailImage(imgFile, w, h, prevfix, force);
    }
    
    public void thumbnailImage(String imagePath, int w, int h, boolean force){
        thumbnailImage(imagePath, w, h, DEFAULT_PREVFIX, force);
    }
    
    public void thumbnailImage(String imagePath, int w, int h){
        thumbnailImage(imagePath, w, h, DEFAULT_FORCE);
    }
    
    public static void main(String[] args) {
        new ImageUtil().thumbnailImage("imgs/Tulips.jpg", 100, 150);
    }

}

效果:(原图是电脑"图片"文件夹下的郁金香图片,大小1024*768,生成的图片为200*150大小,保持4:3的比例)
 

JAVA 截取图片局部内容: 

package com.ares.image.test;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ares.slf4j.test.Slf4jUtil;

/**
 * <p>Title: ImageUtil </p>
 * <p>Description: </p>
 * <p>Email: icerainsoft@hotmail.com </p> 
 * @author Ares
 * @date 2014年10月28日 上午10:24:26
 */
public class ImageUtil {

    static {
        Slf4jUtil.buildSlf4jUtil().loadSlf4j();
    }
    private Logger log = LoggerFactory.getLogger(getClass());
    
    private static String DEFAULT_THUMB_PREVFIX = "thumb_";
    private static String DEFAULT_CUT_PREVFIX = "cut_";
    private static Boolean DEFAULT_FORCE = false;
    
    
    /**
     * <p>Title: cutImage</p>
     * <p>Description:  根据原图与裁切size截取局部图片</p>
     * @param srcImg    源图片
     * @param output    图片输出流
     * @param rect        需要截取部分的坐标和大小
     */
    public void cutImage(File srcImg, OutputStream output, java.awt.Rectangle rect){
        if(srcImg.exists()){
            java.io.FileInputStream fis = null;
            ImageInputStream iis = null;
            try {
                fis = new FileInputStream(srcImg);
                // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
                String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("]", ",");
                String suffix = null;
                // 获取图片后缀
                if(srcImg.getName().indexOf(".") > -1) {
                    suffix = srcImg.getName().substring(srcImg.getName().lastIndexOf(".") + 1);
                }// 类型和图片后缀全部小写,然后判断后缀是否合法
                if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()+",") < 0){
                    log.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types);
                    return ;
                }
                // 将FileInputStream 转换为ImageInputStream
                iis = ImageIO.createImageInputStream(fis);
                // 根据图片类型获取该种类型的ImageReader
                ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next();
                reader.setInput(iis,true);
                ImageReadParam param = reader.getDefaultReadParam();
                param.setSourceRegion(rect);
                BufferedImage bi = reader.read(0, param);
                ImageIO.write(bi, suffix, output);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if(fis != null) fis.close();
                    if(iis != null) iis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            log.warn("the src image is not exist.");
        }
    }
    
    public void cutImage(File srcImg, OutputStream output, int x, int y, int width, int height){
        cutImage(srcImg, output, new java.awt.Rectangle(x, y, width, height));
    }
    
    public void cutImage(File srcImg, String destImgPath, java.awt.Rectangle rect){
        File destImg = new File(destImgPath);
        if(destImg.exists()){
            String p = destImg.getPath();
            try {
                if(!destImg.isDirectory()) p = destImg.getParent();
                if(!p.endsWith(File.separator)) p = p + File.separator;
                cutImage(srcImg, new java.io.FileOutputStream(p + DEFAULT_CUT_PREVFIX + "_" + new java.util.Date().getTime() + "_" + srcImg.getName()), rect);
            } catch (FileNotFoundException e) {
                log.warn("the dest image is not exist.");
            }
        }else log.warn("the dest image folder is not exist.");
    }
    
    public void cutImage(File srcImg, String destImg, int x, int y, int width, int height){
        cutImage(srcImg, destImg, new java.awt.Rectangle(x, y, width, height));
    }
    
    public void cutImage(String srcImg, String destImg, int x, int y, int width, int height){
        cutImage(new File(srcImg), destImg, new java.awt.Rectangle(x, y, width, height));
    }
    /**
     * <p>Title: thumbnailImage</p>
     * <p>Description: 根据图片路径生成缩略图 </p>
     * @param imagePath    原图片路径
     * @param w            缩略图宽
     * @param h            缩略图高
     * @param prevfix    生成缩略图的前缀
     * @param force        是否强制按照宽高生成缩略图(如果为false,则生成最佳比例缩略图)
     */
    public void thumbnailImage(File srcImg, OutputStream output, int w, int h, String prevfix, boolean force){
        if(srcImg.exists()){
            try {
                // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
                String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("]", ",");
                String suffix = null;
                // 获取图片后缀
                if(srcImg.getName().indexOf(".") > -1) {
                    suffix = srcImg.getName().substring(srcImg.getName().lastIndexOf(".") + 1);
                }// 类型和图片后缀全部小写,然后判断后缀是否合法
                if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()+",") < 0){
                    log.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types);
                    return ;
                }
                log.debug("target image's size, width:{}, height:{}.",w,h);
                Image img = ImageIO.read(srcImg);
                // 根据原图与要求的缩略图比例,找到最合适的缩略图比例
                if(!force){
                    int width = img.getWidth(null);
                    int height = img.getHeight(null);
                    if((width*1.0)/w < (height*1.0)/h){
                        if(width > w){
                            h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0)));
                            log.debug("change image's height, width:{}, height:{}.",w,h);
                        }
                    } else {
                        if(height > h){
                            w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0)));
                            log.debug("change image's width, width:{}, height:{}.",w,h);
                        }
                    }
                }
                BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Graphics g = bi.getGraphics();
                g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
                g.dispose();
                // 将图片保存在原目录并加上前缀
                ImageIO.write(bi, suffix, output);
                output.close();
            } catch (IOException e) {
               log.error("generate thumbnail image failed.",e);
            }
        }else{
            log.warn("the src image is not exist.");
        }
    }
    public void thumbnailImage(File srcImg, int w, int h, String prevfix, boolean force){
        String p = srcImg.getAbsolutePath();
        try {
            if(!srcImg.isDirectory()) p = srcImg.getParent();
            if(!p.endsWith(File.separator)) p = p + File.separator;
            thumbnailImage(srcImg, new java.io.FileOutputStream(p + prevfix +srcImg.getName()), w, h, prevfix, force);
        } catch (FileNotFoundException e) {
            log.error("the dest image is not exist.",e);
        }
    }
    
    public void thumbnailImage(String imagePath, int w, int h, String prevfix, boolean force){
        File srcImg = new File(imagePath);
        thumbnailImage(srcImg, w, h, prevfix, force);
    }
    
    public void thumbnailImage(String imagePath, int w, int h, boolean force){
        thumbnailImage(imagePath, w, h, DEFAULT_THUMB_PREVFIX, DEFAULT_FORCE);
    }
    
    public void thumbnailImage(String imagePath, int w, int h){
        thumbnailImage(imagePath, w, h, DEFAULT_FORCE);
    }
    
    public static void main(String[] args) {
        new ImageUtil().thumbnailImage("imgs/Tulips.jpg", 150, 100);
        new ImageUtil().cutImage("imgs/Tulips.jpg","imgs", 250, 70, 300, 400);
    }

}

效果如下:(使用在上传图片时取缩略图和截图的地方,例如,图像截取并缩略)
 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1221707.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Java中利用OpenCV进行人脸识别

OpenCV 概述 ​ OpenCV&#xff08;Open Source Computer Vision Library&#xff09;是一个开源计算机视觉库&#xff0c;它提供了丰富的工具和算法&#xff0c;用于处理图像和视频数据。该库由一系列高效的计算机视觉算法组成&#xff0c;涵盖了许多领域&#xff0c;包括目…

K8S1.23.5部署(此前1.17版本步骤囊括)及问题记录

应版本需求&#xff0c;升级容器版本为1.23.5 kubernetes组件 一个kubernetes集群主要由控制节点&#xff08;master&#xff09;与工作节点&#xff08;node&#xff09;组成&#xff0c;每个节点上需要安装不同的组件。 master控制节点&#xff1a;负责整个集群的管理。 …

Pytorch torch.dot、torch.mv、torch.mm、torch.norm的用法详解

torch.dot的用法&#xff1a; 使用numpy求点积&#xff0c;对于二维的且一个二维的维数为1 torch.mv的用法&#xff1a; torch.mm的用法 torch.norm 名词解释&#xff1a;L2范数也就是向量的模&#xff0c;L1范数就是各个元素的绝对值之和例如&#xff1a;

RMI协议详解

前言特点应用示例存在的问题应用场景拓展 前言 RMI&#xff08;Remote Method Invocation&#xff0c;远程方法调用&#xff09;是Java中的一种远程通信协议&#xff0c;用于实现跨网络的对象方法调用。RMI协议基于Java的分布式计算&#xff0c;可以让客户端程序调用远程服务器…

MIB 6.1810实验Xv6 and Unix utilities(5)find

难度:moderate Write a simple version of the UNIX find program for xv6: find all the files in a directory tree with a specific name. Your solution should be in the file user/find.c. 题目要求&#xff1a;实现find &#xff0c;即在某个路径中&#xff0c;找出某…

Babyk勒索病毒数据集恢复,计算机服务器中了babyk勒索病毒怎么办?

计算机网络技术的不断应用&#xff0c;为企业的生产运营提供了极大便利&#xff0c;网络技术的不断发展也带来了许多网络安全隐患&#xff0c;近期&#xff0c;云天数据恢复中心陆续接到许多企业的求助&#xff0c;企业的计算机服务器遭到了babyk勒索病毒的攻击&#xff0c;导致…

nodejs+vue杰和牧场管理系统的设计与实现-微信小程序-安卓-python-PHP-计算机毕业设计

系统涉及的对象是奶牛。 系统使用员工有管理员和普通员工。 管理员有修改的权限&#xff0c;普通员工没有。系统包含新闻功能&#xff0c;最好是有个后台管理&#xff0c;在后台输入新闻标题和内容&#xff0c;插入图片&#xff0c;在网页上就可以展示。最好再有个轮播图。 新闻…

我的 2023 秋招总结,拿到了大厂offer

2023秋招小结 前言 & 介绍 作为2024年毕业的学生&#xff0c;在2023年也就是今年秋招。 现在秋招快结束了&#xff0c;人生可能没有几次秋招的机会&#xff08;应该就一次&#xff0c;最多两次吧哈哈&#xff09;&#xff0c;也有一点感悟&#xff0c;所以小小总结一下。…

基于SSM的项目管理系统设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用JSP技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

requests爬虫IP连接初始化问题及解决方案

问题背景 在使用HTTPS爬虫IP连接时&#xff0c;如果第一次请求是chunked方式&#xff0c;那么HTTPS爬虫IP连接将不会被初始化。这个问题可能会导致403错误&#xff0c;或者在使用HTTPS爬虫IP时出现SSL错误。 解决方案 为了解决这个问题&#xff0c;我们可以在requests库的ada…

从傅里叶变换,到短时傅里叶变换,再到小波分析(CWT),看这一篇就够了(附MATLAB傻瓜式实现代码)

本专栏中讲了很多时频域分析的知识&#xff0c;不过似乎还没有讲过时频域分析是怎样引出的。 所以本篇将回归本源&#xff0c;讲一讲从傅里叶变换→短时傅里叶变换→小波分析的过程。 为了让大家更直观得理解算法原理和推导过程&#xff0c;这篇文章将主要使用图片案例。 一…

sqlite与mysql的差异

差异点 安装过程&#xff1a;MySQL服务器通常需要单独安装&#xff0c;这涉及下载适用于特定操作系统的MySQL安装程序&#xff0c;运行安装程序并按照指示完成安装过程。SQLite作为嵌入式数据库&#xff0c;可以直接使用其库文件&#xff0c;不需要单独的安装过程。 配置和管理…

虚拟局域网VLAN_基础知识

虚拟局域网VLAN的概述 一. 虚拟局域网VLAN的诞生背景 将多个站点通过一个或多个以太网交换机连接起来就构建出了交换式以太网。 交换式以太网中的所有站点都属于同一个广播域。 随着交换式以太网规模的扩大&#xff0c;广播域也相应扩大。 巨大的广播域会带来一系列问题: 广…

【案例分享】BenchmarkSQL 5.0 压测 openGauss 5.0.0

一、前言 本次BenchmarkSQL 压测openGauss仅作为学习使用压测工具测试tpcc为目的&#xff0c;并不代表数据库性能如本次压测所得数据。实际生产性能压测&#xff0c;还需结合服务器软硬件配置、数据库性能参数调优、BenchmarkSQL 配置文件参数相结合&#xff0c;是一个复杂的过…

解决 vite 4 开发环境和生产环境打包后空白、配置axios跨域、nginx代理本地后端接口问题

1、解决打包本地无法访问空白 首先是pnpm build 打包后直接在dist访问&#xff0c;是访问不了的&#xff0c;需要开启服务 终端输入 npm install -g serve 然后再输入 serve -s dist 就可以访问了 但要保证 路由模式是&#xff1a;createWebHashHistory 和vite.conffig.j…

linux关于cmake,makefile和gdb的使用

c文件的编译 安装环境(centos 7) 检查命令是否齐全 gcc --version g --version gdb–version 安装命令 yum -y install gcc-c安装g命令&#xff08;用于编译c/c文件&#xff09; yum -y install gcc安装gcc命令(用于编译c文件&#xff09; 每个都出现版本号&#xff0c;证明…

Sentinel 熔断规则 (DegradeRule)

Sentinel 是面向分布式、多语言异构化服务架构的流量治理组件&#xff0c;主要以流量为切入点&#xff0c;从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。 SpringbootDubboNacos 集成 Sentinel&…

Flutter笔记:桌面应用 窗口定制库 bitsdojo_window

Flutter笔记 桌面应用窗口管理库 bitsdojo_window 作者&#xff1a;李俊才 &#xff08;jcLee95&#xff09;&#xff1a;https://blog.csdn.net/qq_28550263 邮箱 &#xff1a;291148484163.com 本文地址&#xff1a;https://blog.csdn.net/qq_28550263/article/details/13446…

zookeperkafka学习

1、why kafka 优点 缺点kafka 吞吐量高&#xff0c;对批处理和异步处理做了大量的设计&#xff0c;因此Kafka可以得到非常高的性能。延迟也会高&#xff0c;不适合电商场景。RabbitMQ 如果有大量消息堆积在队列中&#xff0c;性能会急剧下降每秒处理几万到几十万的消息。如果…

如何用继承和多态来打印个人信息

1 问题 在python中的数据类型中&#xff0c;我们常常运用继承和多态。合理地使用继承和多态可以增强程序的可扩展性使代码更简洁。那么如何使用继承和多态来打印个人信息&#xff1f; 2 方法 打印基本信息添加子类&#xff0c;再定义一个class&#xff0c;可以直接从Person类继…