Java处理图片三部曲

阅读更多
1.等比例缩小或放大图片

/**
 * Create time May 31, 2009 4:33:31 PM
 */
package com.yd.image;

import java.awt.Canvas;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.AreaAveragingScaleFilter;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.io.File;

import javax.imageio.ImageIO;

/**
 * 

Title: ZoomImage

*

Description:

* * @author Yaodi * @version 1.0 */ public class ZoomImage { private static Component component = new Canvas(); private static String[] imageFormatArray = new String[] { ".jpg", ".jpeg", ".gif", ".png", ".bmp" };//pcx/tga/tif这三种格式目前还不支持 /** * 校验图像文件的格式是否可以进行缩放 */ public boolean verifyImageFormat(String fileName) { boolean result = false; for (int i = 0; i < imageFormatArray.length; i++) { if (fileName.toLowerCase().lastIndexOf(imageFormatArray[i]) == (fileName .length() - imageFormatArray[i].length())) { result = true; break; } } return result; } /** * 将目录下的所有图像进行放大缩小 * * @param strDir 图像的目录 * @param zoomRatio 放大缩小的倍率 * @param rebuild 是否重新创建,即已经存在的图像是否覆盖重建 * @throws Exception */ public void zoom(String strDir, double zoomRatio, boolean rebuild) throws Exception { File fileDir = new File(strDir); if (!fileDir.exists()) { return; } String dirTarget = strDir + "/small" + zoomRatio; File fileTarget = new File(dirTarget); if (!fileTarget.exists()) { fileTarget.mkdir(); } File[] files = fileDir.listFiles(); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < files.length; i++) { String fileFullName = files[i].getCanonicalPath(); String fileShortName = files[i].getName(); if (!new File(fileFullName).isDirectory())// 排除二级目录,如果想就再递归一次,这里省略 { if (verifyImageFormat(fileShortName)) { stringBuilder = new StringBuilder(); stringBuilder.append(dirTarget).append("/").append( fileShortName); if (!new File(stringBuilder.toString()).exists() || rebuild) { try { createZoomSizeImage(fileFullName, stringBuilder .toString(), zoomRatio); } catch (Exception e) { } } } } } } /** * 按比例进行放大或缩小图像,zoomRatio = 1为原大,zoomRatio > 1为放大,zoomRatio < 1 为缩小 */ public void createZoomSizeImage(String fileName, String fileNameTarget, double zoomRatio) throws Exception { Image image = ImageIO.read(new File(fileName)); int width = new Double(image.getWidth(null) * zoomRatio).intValue(); int height = new Double(image.getHeight(null) * zoomRatio).intValue(); AreaAveragingScaleFilter areaAveragingScaleFilter = new AreaAveragingScaleFilter( width, height); FilteredImageSource filteredImageSource = new FilteredImageSource(image .getSource(), areaAveragingScaleFilter); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); Graphics graphics = bufferedImage.createGraphics(); graphics.drawImage(component.createImage(filteredImageSource), 0, 0, null); ImageIO.write(bufferedImage, "JPEG", new File(fileNameTarget)); } public static void main(String[] args) throws Exception { ZoomImage zoomImage = new ZoomImage(); zoomImage.zoom("F:/pic", 0.25, false);// 缩小2倍 //zoomImage.zoom("F:/pic",2,true);// 放大2倍 System.out.println("************THEEND************"); } }


2.按坐标裁切图片

/**
 * Create time May 31, 2009 4:33:31 PM
 */
package com.yd.image;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

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


/**
 * 

Title: CutImage

*

Description:

* * @author Yaodi * @version 1.0 */ public class CutImage { private static int x_share = 8; //x切片份数 private static int y_share = 10; //y切片份数 private static String srcpath = "F:/pic/xiaohei.jpg"; //源图片路径名称 private static String subpath = "F:/pic/cut/"; //剪切图片存放的目录 private int x; //剪切点x坐标 private int y; //剪切点y坐标 private int width; //剪切点宽度 private int height; //剪切点高度 private int num; public CutImage() { } public CutImage(int x, int y, int width, int height, int num) { this.x = x; this.y = y; this.width = width; this.height = height; this.num = num; } /** * 对图片裁剪,并把裁剪完的新图片保存 */ public void cut() throws IOException { FileInputStream is = null; ImageInputStream iis = null; try { // 读取图片文件 is = new FileInputStream(srcpath); /** * 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader 声称能够解码指定格式。 * 参数:formatName - 包含非正式格式名称 . (例如 "jpeg" 或 "tiff")等 。 */ Iterator it = ImageIO .getImageReadersByFormatName("jpg"); ImageReader reader = it.next(); // 获取图片流 iis = ImageIO.createImageInputStream(is); /** * iis:读取源.true:只向前搜索.将它标记为 ‘只向前搜索’。 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许 * reader 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。 */ reader.setInput(iis, true); /** *

* 描述如何对流进行解码的类 *

* .用于指定如何在输入时从 Java Image I/O 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 将从其 * ImageReader 实现的 getDefaultReadParam 方法中返回 ImageReadParam 的实例。 */ ImageReadParam param = reader.getDefaultReadParam(); /** * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域,通过 Rectangle 对象 * 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。 */ Rectangle rect = new Rectangle(x, y, width, height); // 提供一个 BufferedImage,将其用作解码像素数据的目标。 param.setSourceRegion(rect); /** * 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象,并将 它作为一个完整的 * BufferedImage 返回。 */ BufferedImage bi = reader.read(0, param); // 保存新图片 ImageIO.write(bi, "jpg", new File(subpath + num + ".jpg")); } finally { if (is != null) is.close(); if (iis != null) iis.close(); } } public static void main(String[] args) throws IOException { BufferedImage bufferedImage = ImageIO.read(new File(srcpath)); File file = new File(subpath); //创建切片存放的目录 file.mkdirs(); int init_width = bufferedImage.getWidth(); //获得原始图片的宽 int init_height = bufferedImage.getHeight(); //获得原始图片的高 int x = 0; //x坐标点 int y = 0; //y坐标点 int width = init_width / x_share; //裁切后图片的宽 int height = init_height / y_share; //裁切后图片的高 int sum = (init_width / width) * (init_height / height); //获得切片的总数 for (int i = 1; i <= sum; i++) { if (x == init_width) { x = 0; y = y + height; //y坐标移动 } CutImage ci = new CutImage(x, y, width, height, i); x = x + width; //x坐标移动 try { ci.cut(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("************THEEND************"); } }



图片宽和高必须要被切片份数整除

3.判断图片是否相同

/**
 * Create time May 31, 2009 4:33:31 PM
 */
package com.yd.image;

import java.io.File;
import java.security.MessageDigest;

/**
 * 

Title: MD5Image

*

Description:

* * @author Yaodi * @version 1.0 */ public class MD5Image { /** * MD5加密的方式判断图片是否相同 */ public static String MD5(byte[] s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };//16进制字符 try { byte[] strTemp = s; MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(strTemp); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0;//移位 输出字符串 for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { return null; } } public static void main(String[] args) { //44f24b510805d6c8ed2aec46817ebb5e File file = new File("F:/pic/xiaohei.jpg"); byte[] b = new byte[(int) file.length()]; System.out.println(MD5Image.MD5(b)); } }


通过生成的MD5码,进行判断筛选出文件夹中相同的图片

你可能感兴趣的:(Java,IIS,F#,框架,Security)