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,[url]http://www.jmagick.org/lenya/jmagick/live/download.html[/url],正在验证中……
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值