图片处理

package org.image;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.ImageIcon;

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

public class ImageUtil {
public static double ratio(File file) throws IOException {
ImageIcon ii = new ImageIcon(file.getCanonicalPath());
Image image = ii.getImage();

int width = image.getWidth(null);
int height = image.getHeight(null);
if (width > height) {
return (double)height / width;
} else {
return (double)width / height;
}
}
/**
* 图片压缩
*/
public static void reszie(File file, File resizeFile, int newWidth, float quality) throws IOException {
if (quality > 1) {
throw new IllegalArgumentException("quality 必须介于0到1之间");
}
ImageIcon ii = new ImageIcon(file.getCanonicalPath());
Image image = ii.getImage();
Image resizeImage = null;

int width = image.getWidth(null);
int height = image.getHeight(null);

if (width > height) {
resizeImage = image.getScaledInstance(newWidth, newWidth * height / width, Image.SCALE_SMOOTH);
} else {
resizeImage = image.getScaledInstance(newWidth * width / height, newWidth, Image.SCALE_SMOOTH);
}

Image temp = new ImageIcon(resizeImage).getImage();

BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

Graphics graphics = bufferedImage.createGraphics();

graphics.setColor(Color.white);
graphics.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));;
graphics.drawImage(temp, 0, 0, null);
graphics.dispose();

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);

FileOutputStream out = new FileOutputStream(resizeFile);

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);

param.setQuality(quality, true);

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

}

 

posted @ 2016-02-22 19:35  ltang0  阅读(165)  评论(0编辑  收藏  举报