`
雨打蕉叶
  • 浏览: 238292 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

java剪裁图片的一些收获

阅读更多
最近要实现把用户上传的图片转换为500宽,245*200,102*85,大小的格式,要保证图片质量,又要高效率。下面是我试过的一下方法。
方法一:效率高,质量低

import java.awt.Graphics;

import java.awt.image.BufferedImage;
import java.io.File;

import java.io.IOException;


import javax.imageio.ImageIO;


public class ImageUtils{
	

	/**
	 * 对图片进行缩小
	 * @param originalImage 原始图片
	 * @param times 缩小倍数
	 * @return 缩小后的图像
	 */
	public static BufferedImage  zoomImage(BufferedImage  originalImage,double  times){
		int width = (int) ((int)originalImage.getWidth()*times);
		int height = (int) ((int)originalImage.getHeight()*times);
		System.out.println("width:"+width+" height:"+height);
		BufferedImage newImage = new BufferedImage(width,height,originalImage.getType());
		Graphics g = newImage.getGraphics();
		g.drawImage(originalImage, 0,0,width,height,null);
		g.dispose();
		return newImage;
	}
	

	/**
	 * 截取图片
	 * @param path 图片路径
	 * @param x 开始位置x坐标
	 * @param y 开始位置y坐标
	 * @param width 宽度
	 * @param height 高度
	 * @return 图片保存的url
	 */

	public static BufferedImage cutting(BufferedImage bufferedImage,int x,int y,int width,int height){
			return bufferedImage.getSubimage(x, y, width, height);
	}
	/**
	 * 处理图片 获得102*85,245*200,宽500等比例缩放
	 * @param path 图片路径
	 * @return 处理成功返回true,处理失败返回false
	 */
	public static boolean afterPostPhoto(String path){
		BufferedImage bufferedImage = null;
		String suffix=path.substring(path.lastIndexOf(".")+1, path.length());
		
		try {
			bufferedImage =  ImageIO.read(new File(path));
			double x=bufferedImage.getWidth();
			double y=bufferedImage.getHeight();
			System.out.println("x="+x+",y="+y);
			if(x>500){
				double times=500/x;
				
			
				ImageIO.write(zoomImage(bufferedImage, times), suffix, new File(path.substring(0, path.lastIndexOf("."))+"L"+path.substring(path.lastIndexOf("."), path.length())));
			}
			if(x>245){
				
				double times;
				if(x/y>1.225){
					 times=200/y;
					
				}else{
					 times=245/x;
				}
				
				ImageIO.write(cutting(zoomImage(bufferedImage, times), 0, 0, 245, 200), suffix, new File(path.substring(0, path.lastIndexOf("."))+"M"+path.substring(path.lastIndexOf("."), path.length())));
			}
			
			if(x>102){
				double times;
				if(x/y>1.2){
					 times=85/y;
					
				}else{
					 times=102/x;
				}
				
				ImageIO.write(cutting(zoomImage(bufferedImage, times), 0, 0, 102, 85), suffix, new File(path.substring(0, path.lastIndexOf("."))+"S"+path.substring(path.lastIndexOf("."), path.length())));
			
			}
			
		} catch (IOException e) {
			
			e.printStackTrace();
			return false;
		}
			return true;
	}
	public static boolean afterSetIcon(String path){
		BufferedImage bufferedImage = null;
		double times;
		String suffix=path.substring(path.lastIndexOf(".")+1, path.length());
		try {
			bufferedImage =  ImageIO.read(new File(path));
		} catch (IOException e) {
			
			e.printStackTrace();
			return false;
		}
		double x=bufferedImage.getWidth();
		double y=bufferedImage.getHeight();
		if(x/y>1){
			 times=x/y;
		}
		else if(y/x>1){
			times=y/x;
		}
		return true;
	}
	/**
	 * 检查图片分辨率是否大于300*200
	 * 大于300*200返回true,执行上传,否则返回
	 * false并删除图片
	 * @param path 图片路径
	 * @return 大于300*200返回true,否则返回false
	 */
	public static boolean checkUpload(String path){
		BufferedImage bufferedImage = null;
		
		try {
			bufferedImage =  ImageIO.read(new File(path));
			double x=bufferedImage.getWidth();
			double y=bufferedImage.getHeight();
			if(x<300||y<200){
				return false;
			}
		} catch (IOException e) {
			
			e.printStackTrace();
			return false;
		}
		return true;
		
	}
	public static void main(String[] args) {
		
		afterPostPhoto("F:/照片/春天的足迹/1.jpg");
	//	System.out.println(x/y);
	}

方法二:质量高,效率低
package image.too;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.Kernel;
import java.awt.image.ConvolveOp;

public class ImagePro {
	/**
	 * 图片缩放
	 * 
	 * @param originalFile
	 *            源文件
	 * @param resizedFile
	 *            目标文件
	 * @param newWidth
	 *            新图片的宽度
	 * @param quality
	 *            成像质量
	 * @throws IOException
	 */
	public static void resize(File originalFile, File resizedFile,
			int newWidth, float quality) throws IOException {
		BufferedImage bufferedImage = resize(originalFile, newWidth, quality);

		savaImage(bufferedImage, resizedFile);

	}

	public static void savaImage(BufferedImage bufferedImage, File resizedFile)
			throws ImageFormatException, IOException {
		FileOutputStream out = new FileOutputStream(resizedFile);

		// Encodes image as a JPEG data stream
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

		JPEGEncodeParam param = encoder
				.getDefaultJPEGEncodeParam(bufferedImage);

		param.setQuality(1.0f, true);

		encoder.setJPEGEncodeParam(param);
		encoder.encode(bufferedImage);
	}

	/** 截取图片 */
	public static void cutting(File file, File newFile, int x, int y,
			int width, int height) {
		try {
			String endName = file.getName();
			endName = endName.substring(endName.lastIndexOf(".") + 1);
			Iterator<ImageReader> readers = ImageIO
					.getImageReadersByFormatName(endName);
			ImageReader reader = (ImageReader) readers.next();
			InputStream is = new FileInputStream(file);
			ImageInputStream iis = ImageIO.createImageInputStream(is);
			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);
			ImageOutputStream out = ImageIO
					.createImageOutputStream(new FileOutputStream(newFile));
			ImageIO.write(bi, endName, out);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static BufferedImage resize(File originalFile, int newWidth,
			float quality) throws IOException {

		if (quality > 1) {
			throw new IllegalArgumentException(
					"Quality has to be between 0 and 1");
		}

		ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
		Image i = ii.getImage();
		Image resizedImage = null;

		int iWidth = i.getWidth(null);
		int iHeight = i.getHeight(null);

		if (iWidth > iHeight) {
			resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight)
					/ iWidth, Image.SCALE_AREA_AVERAGING);
		} else {
			resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight,
					newWidth, Image.SCALE_AREA_AVERAGING);
		}

		// This code ensures that all the pixels in the image are loaded.
		Image temp = new ImageIcon(resizedImage).getImage();

		// Create the buffered image.
		BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),

		temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

		// Copy image to buffered image.
		Graphics g = bufferedImage.createGraphics();

		// Clear background and paint the image.
		g.setColor(Color.white);
		g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
		g.drawImage(temp, 0, 0, null);
		g.dispose();

		// Soften.
		float softenFactor = 0.05f;
		float[] softenArray = { 0, softenFactor, 0, softenFactor,
				1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0 };
		Kernel kernel = new Kernel(3, 3, softenArray);
		ConvolveOp cOp = new ConvolveOp(kernel,

		ConvolveOp.EDGE_NO_OP, null);
		bufferedImage = cOp.filter(bufferedImage, null);

		return bufferedImage;
	}

	/**
	 * 处理图片 获得102*85,245*200,宽500等比例缩放
	 * 
	 * @param path
	 *            图片路径
	 * @return 处理成功返回true,处理失败返回false
	 */
	public static boolean process(String path) {
		File file = new File(path);
		BufferedImage bufferedImage = null;
	

		try {
			bufferedImage = ImageIO.read(new File(path));
			double x = bufferedImage.getWidth();
			double y = bufferedImage.getHeight();
			System.out.println("x=" + x + ",y=" + y);
			if (x > 500) {
				resize(file,
						new File(path.substring(0, path.lastIndexOf("."))
								+ "L"
								+ path.substring(path.lastIndexOf("."),
										path.length())), 500, 1.0f);
			} else {

				copyImage(
						file,
						new File(path.substring(0, path.lastIndexOf("."))
								+ "L"
								+ path.substring(path.lastIndexOf("."),
										path.length())));
			}

			if (x > 245) {

				int iWidth;
				if (x / y > 1.225) {
					iWidth = (int) (x * 200 / y);

				} else {
					iWidth = 245;
				}
				resize(file,
						new File(path.substring(0, path.lastIndexOf("."))
								+ "M"
								+ path.substring(path.lastIndexOf("."),
										path.length())), iWidth, 1.0f);

			} else {

				copyImage(
						file,
						new File(path.substring(0, path.lastIndexOf("."))
								+ "M"
								+ path.substring(path.lastIndexOf("."),
										path.length())));
			}

			if (x > 102) {
				int iWidth;
				if (x / y > 1.2) {
					iWidth = (int) (x * 85 / y);

				} else {
					iWidth = 102;
				}
				resize(file,
						new File(path.substring(0, path.lastIndexOf("."))
								+ "S"
								+ path.substring(path.lastIndexOf("."),
										path.length())), iWidth, 1.0f);

			} else {

				copyImage(
						file,
						new File(path.substring(0, path.lastIndexOf("."))
								+ "S"
								+ path.substring(path.lastIndexOf("."),
										path.length())));
			}

		} catch (IOException e) {

			e.printStackTrace();
		}
		return true;
	}

	/**
	 * 复制文件
	 * 
	 * @param source
	 *            源文件
	 * @param destination
	 *            目标文件
	 */
	public static void copyFile(File source, File destination) {

		FileInputStream sourceFile = null;
		FileOutputStream destinationFile = null;
		try {

			destination.createNewFile();

			sourceFile = new FileInputStream(source);
			destinationFile = new FileOutputStream(destination);
			BufferedReader br = new BufferedReader(new FileReader(source));
			// ByteArrayInputStream bin=new ByteArrayInputStream(br.r)
			BufferedWriter bw = new BufferedWriter(new FileWriter(destination));

			String str = null;
			while ((str = br.readLine()) != null) {
				bw.write(str);
				bw.newLine();
				bw.flush();
			}

		} catch (FileNotFoundException f) {
		} catch (IOException e) {
		} finally {

			try {
				sourceFile.close();
			} catch (Exception e) {
			}
			try {
				destinationFile.close();
			} catch (Exception e) {
			}
		}
	}

	public static void copyImage(File source, File destination) {

		FileInputStream fi = null;
		try {
			fi = new FileInputStream(source);
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		}
		BufferedInputStream in = new BufferedInputStream(fi);
		FileOutputStream fo = null;
		try {
			fo = new FileOutputStream(destination);
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		}
		BufferedOutputStream out = new BufferedOutputStream(fo);

		byte[] buf = new byte[1024];
		int len;
		try {
			len = in.read(buf);
			while (len != -1) {
				out.write(buf, 0, len);
				len = in.read(buf);
			}
			out.close();
			fo.close();
			in.close();
			fi.close();
		} catch (IOException e) {

			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws IOException {
		// File originalImage = new File("C:\\11.jpg");
		// resize(originalImage, new File("c:\\11-0.jpg"),150, 0.7f);
		// resize(originalImage, new File("c:\\11-1.jpg"),150, 1f);
		// File originalImage = new File("E:/1.jpg");
		// resize(originalImage, new File("E:/1203-0.png"), 500, 0.7f);
		// resize(originalImage, new File("E:/1203-1.png"), 500, 1f);
		long time = System.currentTimeMillis();
		process("E:/1.jpg");
		System.out.println(System.currentTimeMillis() - time);
		// copyImage(new File("E:/Post.java"), new File("E:/Post2.java"));
		// copyImage("E:/1.jpg","E:/1_0.jpg");
	}
}

在网上找了找相关的资料,发现有个开源的框架jmagick.org,http://www.jmagick.org/lenya/jmagick/live/download.html,正在验证中……
分享到:
评论

相关推荐

    java坦克大战

    本项目是基于Java语言实现的坦克大战图片版,原汁原味地复刻了尚学堂视频教程中的内容,几乎未做任何改动,对于想要学习Java图形界面编程和游戏开发的初学者来说,是一个理想的实践项目。 首先,我们来看看“Java...

    安卓拼图游戏

    这个过程中,可能涉及到了图像处理库,如OpenCV,用于图像读取、裁剪和保存。同时,为了保证游戏的趣味性和挑战性,开发者还需要设计不同的难度级别,如拼图块的数量和打乱程度。 在游戏的交互设计上,玩家可以通过...

    以下是常见的C++笔试面试题及其核心知识点解析,帮助您系统复习

    以下是常见的C++笔试面试题及其核心知识点解析,帮助您系统复习

    计算机短期培训教案.pdf

    计算机短期培训教案.pdf

    计算机二级Access笔试题库.pdf

    计算机二级Access笔试题库.pdf

    下是一份关于C++毕业答辩的心得总结,内容涵盖技术准备、答辩技巧和注意事项,供参考

    下是一份关于C++毕业答辩的心得总结,内容涵盖技术准备、答辩技巧和注意事项,供参考

    基于IPU的Cassandra集群技术验证与优化:苹果公司内部技术培训

    内容概要:本文档详细介绍了英特尔为苹果公司构建的基于智能处理单元(IPU)的Cassandra集群的技术验证(PoC)。主要内容涵盖IPU存储用例、已建存储PoC、MEV到MMG400的过渡、苹果构建IPU-Cassandra集群的动机以及PoC开发进展。文档还探讨了硬件配置、软件环境设置、性能调优措施及其成果,特别是针对延迟和吞吐量的优化。此外,文档展示了六节点Cassandra集群的具体架构和测试结果,强调了成本和复杂性的降低。 适合人群:对分布式数据库系统、NoSQL数据库、IPU技术感兴趣的IT专业人员和技术管理人员。 使用场景及目标:适用于希望了解如何利用IPU提升Cassandra集群性能的企业技术人员。主要目标是展示如何通过IPU减少服务器部署的成本和功耗,同时提高数据处理效率。 其他说明:文档中涉及的内容属于机密级别,仅供特定授权人员查阅。文中提到的技术细节和测试结果对于评估IPU在大规模数据中心的应用潜力至关重要。

    计算机二级考试C语言题.pdf

    计算机二级考试C语言题.pdf

    计算机发展史.pdf

    计算机发展史.pdf

    计算机仿真技术系统的分析方法.pdf

    计算机仿真技术系统的分析方法.pdf

    yolo编程相关资源,python编程与YOLO算法组成的坐姿检测系统,功能介绍: 一:实时检测学生错误坐姿人数 二:通过前端阿里云平台显示上传数据,实现数据可视化

    yolo编程相关资源,python编程与YOLO算法组成的坐姿检测系统,功能介绍: 一:实时检测学生错误坐姿人数 二:通过前端阿里云平台显示上传数据,实现数据可视化

    办公室网安全监控uptime-kuma,docker镜像离线压缩包

    办公室网安全监控uptime-kuma,docker镜像离线压缩包

    计算机课程设计-网络编程项目源码.zip

    计算机课程设计-网络编程项目源码.zip

    Microsoft.Office.Interop.Excel.dll 用作C#操作打印机

    将该dll包放入项目并引用,可以操作打印机

    杰奇2.3核淡绿小说网站源码+关关采集10.0

    杰奇2.3内核淡绿唯美小说网站源码 PC+手机版 自动采集 全站伪静态,送10.1版本关关采集器

    计算机辅助教学.pdf

    计算机辅助教学.pdf

    天文领域高画质流星与红色精灵闪电监控系统的构建及应用

    内容概要:本文详细介绍了如何利用天文相机和其他相关硬件设备搭建一套高画质、高帧率的流星监控系统,以及针对红色精灵闪电这一特殊自然现象的捕捉方法。文中不仅涵盖了硬件的选择标准如CMOS靶面尺寸、量子效率等重要参数,还提供了基于Python和OpenCV实现的基本监控代码示例,包括亮度突变检测、运动检测算法等关键技术点。此外,对于安装位置的选择、供电方式、成本控制等方面也有具体的指导建议。 适用人群:对天文摄影感兴趣的爱好者,尤其是希望捕捉流星和红色精灵闪电等瞬时天文现象的专业人士或业余玩家。 使用场景及目标:适用于希望搭建个人天文观测站,用于科学研究或个人兴趣爱好的场景。目标是能够稳定可靠地捕捉到流星和红色精灵闪电等难以捉摸的天文现象,为研究提供高质量的数据资料。 其他说明:文中提到的一些技术和方法虽然较为复杂,但对于有一定编程基础和技术动手能力的人来说是非常实用的参考资料。同时,文中提供的省钱技巧也为预算有限的用户提供了一些有价值的建议。

    时间序列分析-基于R(第2版)习题数据

    时间序列分析-基于R(第2版)习题数据

    LabVIEW与阿特拉斯开放式通讯:网口读取PM4000控制器扭矩值的技术详解

    内容概要:本文详细介绍了如何使用LabVIEW通过网口读取阿特拉斯PM4000控制器的扭矩值。主要内容涵盖开放式通讯协议的理解、阿特拉斯调试软件和测试软件的应用、LabVIEW程序的具体实现步骤,包括初始化网络连接、发送读取扭矩值命令、接收并解析扭矩值数据,以及关闭网络连接。文中还提供了多个调试技巧和注意事项,如硬件接线配置、数据解析方法、常见错误及其解决办法,以及性能优化建议。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是那些需要集成阿特拉斯设备并与之进行数据交互的专业人士。 使用场景及目标:适用于需要实时监控和采集阿特拉斯PM4000控制器扭矩值的工业应用场景,旨在提高数据采集效率和准确性,确保设备运行状态的良好监测。 其他说明:文中提供的代码片段和调试经验有助于快速定位和解决问题,提升开发效率。此外,还强调了数据解析过程中需要注意的细节,如字节序问题和超时设置等。

Global site tag (gtag.js) - Google Analytics