Java 图片裁切及放大缩小

news/2024/7/8 15:36:40 标签: Java, Image

   Java 图片裁切及放大缩小, 仅供参考, 要学会举一反三, 其它问题欢迎交流...

 

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * @author Colin Davis ( nilocsivad@hotmail.com )
 *
 */
public final class DealImage {
	
	private File folder;
	public static final String[] ACCEPT_IMG_TYPES = { ".png", ".jpg", ".jpeg" };

	public DealImage(String folder) {
		this.folder = new File(folder);
	}
	
	public void DealImages() throws IOException {
		for ( File file : this.folder.listFiles() ) {
			if ( file.isFile() && this.IsAcceptImage(file) ) {
				this.Write2File(this.Img2Square(file, 200), this.FileSuffix(file), file.getAbsolutePath(), "square");
			}
		}
	}
	
	public boolean IsAcceptImage(File file) {
		boolean accept = false;
		String fileName = file.getName();
		for ( String type : ACCEPT_IMG_TYPES ) {
			if ( fileName.endsWith(type) ) {
				accept = true;
				break;
			}
		}
		return accept;
	}

	public void Cut2Square(final File imgFile, final int sideLen) throws IOException {

		String formatName = FileSuffix(imgFile);

		Image img = this.Img2Square(imgFile, sideLen);

		BufferedImage bufImg = new BufferedImage(sideLen, sideLen, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2d = bufImg.createGraphics(); // ** 创建画板
		
		g2d.drawImage(img, 0, 0, sideLen, sideLen, null); // ** 把 img(图像) 画到指定位置(x:0, y:0)指定区域(x:sideLen + 0, y:sideLen + 0)
		g2d.dispose();
		
		String destFile = imgFile.getAbsolutePath() + ".square" + formatName;
		ImageIO.write(bufImg, formatName.substring(1), new File(destFile));
	}
	
	/**
	 * 缩小, 缩小比例为 图片大小(宽或高)/sideLen
	 */
	private BufferedImage Img2Small(File imgFile, final int sideLen) throws IOException {

		String formatName = FileSuffix(imgFile);
		if (formatName.toLowerCase().equals(".jpeg")) {
			imgFile = RenameJpeg2Jpg(imgFile);
			formatName = ".jpg";
		}

		BufferedImage img = ImageIO.read(imgFile);
		int imgWidth = img.getWidth(), imgHeight = img.getHeight(), newWidth = sideLen, newHeight = sideLen;
		if ( imgHeight > sideLen || imgWidth > sideLen ) {
			float scale = ( imgWidth > imgHeight ? imgWidth * 0.1f / sideLen : imgHeight * 0.1f / sideLen ) + 0.1f;
			newWidth = (int) (imgWidth * scale);
			newHeight = (int) (imgHeight * scale);
		}

		BufferedImage bi = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2d = bi.createGraphics();
		g2d.drawImage(img, 0, 0, newWidth, newHeight, null);
		g2d.dispose();
		
		return bi;
	}
	
	/**
	 * 缩小后到图片变成正方形, 用白色补齐空白区域
	 */
	private BufferedImage Img2Square(File imgFile, int sideLen) throws IOException {
		
		Image img = this.Img2Small(imgFile, sideLen);
		int imgWidth = img.getWidth(null), imgHeight = img.getHeight(null);
		
		sideLen = imgWidth > imgHeight ? imgWidth : imgHeight;

		BufferedImage bufImg = new BufferedImage(sideLen, sideLen, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2d = bufImg.createGraphics();
		
		g2d.setColor(Color.WHITE);
		g2d.fillRect(0, 0, sideLen, sideLen);
		
		int toX = ( sideLen - imgWidth ) / 2, toY = ( sideLen - imgHeight ) / 2;
		
		g2d.drawImage(img, toX, toY, imgWidth, imgHeight, null);
		g2d.dispose();
		
		return bufImg;
	}

	public File RenameJpeg2Jpg(File jpegFile) throws IOException {
		String imgName = jpegFile.getName();
		int idx = imgName.lastIndexOf(".");
		File destFile = new File(jpegFile.getParentFile(), imgName.substring(0, idx) + ".jpg");
		jpegFile.renameTo(destFile);
		return destFile;
	}

	public String FileSuffix(File file) {
		int idx = file.getName().lastIndexOf(".");
		return idx > 0 ? file.getName().substring(idx) : "";
	}
	
	public void Write2File(final BufferedImage img, String fmt, String path, String append) throws IOException {
		String outFile = path + "." + append + fmt;
		ImageIO.write(img, fmt.substring(1), new File(outFile));
	}
	
	public static void main(String[] args) throws IOException {
		DealImage si = new DealImage("/home/cpu/images/");
		si.DealImages();
	}
	
}

 


http://www.niftyadmin.cn/n/1002071.html

相关文章

Camel in action(译文第一章)

1 First steps1.Camel 介绍2.Camel路由First stepsApachecamel 是 一个开源的一体化框架,其目的是使一体化系统更容易。本书的第一章节我们将介绍camel及展示它适合大企事业单位的软件。你将会学习到关于camel的概念及一些专业术语。第二章将介绍camel其中一个最重要…

ThinkPhp使用经验分享

2019独角兽企业重金招聘Python工程师标准>>> 找了一些使用THinkPHP的心得和技巧,分享给大家 约定: 1.所有类库文件必须使用.class.php作为文件后缀,并且类名和文件名保持一致 2.控制器的类名以Action为后 缀 3.模型的类名以Model为后缀,类名第一个字母须大写 4.数据…

网站“防盗链”的几种实现思路

方法1:判断引用地址 这个方法是最早及最常见的方法。所谓判断引用地址,就是判断浏览器请求时HTTP头的Referer字段的值,这个值在asp.net里面可以用 Request.UrlReferrer属性取得。几个例子来说,在正常情况下当用户在浏览 http://u…

git 暂存区

git的分为四个区----工作区,暂存区,版本库和存储区。可以用git diff 去检测工作区,暂存区和版本库之间的不同。git diff --cached 检测工作区和暂存区之间的不同。git diff HEAD 检测工作区和版本区之间的不同。git status 显示工作区&#x…

WinForm 定时器 定时弹出提示框并关闭

WinForm 定时器 定时弹出提示框并关闭 #region 弹框提示并自动关闭 (目的:延迟拍照)/// <summary>/// 关闭标志/// </summary>private const int WM_CLOSE 0x0010;/// <summary>/// 弹框标题, const 类型以便访问查找/// </summary>private const str…

GCD简介

http://blog.csdn.net/gandam19/article/details/17356597转载于:https://blog.51cto.com/8399249/1390899

IOS学习笔记(二)之应用程序UI基础

IOS学习笔记(二)之应用程序UI基础Author:hmjiangqqEmail:jiangqqlmj163.com有第一个IOS应用程序成功试水&#xff0c;趁热打铁,理解一下UI的基础知识(UIWindow与UIView):&#xff08;一): 看下类的关系&#xff1a;直接查看头文件:就知道UIWindow是UIView的子类&#xff0c;可以…

uclibc和glibc的区别

uclibc和glibc的差别分类&#xff1a; 嵌入式系统2007-01-13 22:556196人阅读评论(1)收藏举报linux内核扩展nullstruct网络unixuClibc和Glibc并不相同&#xff0c;两者有许多不同之处&#xff0c;而且以下不同有可能给你带来一些问题.1.uClibc比Glibc小&#xff0c;虽然uClibc和…