高像素清晰缩略图生成(java)
在公司实习的时候还是练了不少代码的,觉得这个类算得上写的比较通用吧,其中也借鉴了别人的算法,贴出来大家共享共同进步。
package com.modules.image;
import com.modules.basicObject;
import java.net.*;
import java.io.*;
import java.awt.image.*;
import java.awt.*;
import com.sun.image.codec.jpeg.*; import javax.imageio.ImageIO;
import javax.imageio.stream.*;
import com.book.db.dbOperator;
import java.sql.ResultSet;
import java.util.*;
import javax.imageio.stream.*;
import javax.imageio.*;
/**
*
Title: Image Process
*
Copyright: Copyright (c) 2006
*
* @Johbin,Wang
* @version 1.0
*/
public class imager extends basicObject {
private Image org_image = null;
private BufferedImage bfd_image = null;
private BufferedImage tag = null;
private String imageName = "";
private String sourceFileURI ="";
private String desFileURI = "";
private String imageType = "jpeg";//defaultf format
private String str_uri=null;
public imager() {
}
public boolean setImage(String m_id,String type)
{
try{
str_uri = getAppPath() + "files/images/";
imageType = type;
imageName = m_id + "." + imageType;
str_uri += imageName;
sourceFileURI = str_uri;
File _file = new File(str_uri);
org_image = javax.imageio.ImageIO.read(_file);
return true;
}
catch(Exception e)
{
this.AddError("set image", e.getMessage()+"
"+imageName+"
"+str_uri+"
");
return false;
}
}
//generate resized image, and put it under images/thumb directory
//add record into database
//return image id if successfully
public String resize(int width,int height,String pos){
try
{
if(org_image!=null)
{
BufferedImage temp = null;
desFileURI = getAppPath() +
"files/images/thumb/"+"SM"+imageName.substring(2); //destination image URI
int _width = org_image.getWidth(null);
int _height = org_image.getHeight(null);
FileOutputStream out=new FileOutputStream(desFileURI);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
if(_width<=width&&_height<=height)
{
if(_width==width&&_height==height)
{
FileInputStream fileis = new FileInputStream(sourceFileURI);
FileOutputStream fileos = new FileOutputStream(desFileURI);
int count;
byte[] buffer = new byte[100];
while(-1 != (count = fileis.read(buffer))){
fileos.write(buffer);
fileos.flush();
}
fileis.close();
fileos.close();
}
else
{
tag = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(org_image,(width-_width)/2,(height-_height)/2,_width,_height,null);
//encoder.encode(tag);
//out.close();
ImageIO.write(temp,imageType,new File(desFileURI));
}
}
else if(_width>width&&_height<=height)
{
//scale the source image
tag = new BufferedImage(_width,height,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(org_image,0,(height-_height)/2,_width,_height,null);
//clip image
if(pos.equalsIgnoreCase("TL")||pos.equalsIgnoreCase("ML")||pos.equalsIgnoreCase("BL"))
{
temp = tag.getSubimage(0,0, width,height);
}
else
if(pos.equalsIgnoreCase("TM")||pos.equalsIgnoreCase("MM")||pos.equalsIgnoreCase("BM"))
{
temp = tag.getSubimage((_width-width)/2,0, width,height);
}
else
{
temp = tag.getSubimage(_width-width,0, width,height);
}
encoder.encode(temp);
//out.close();
//ImageIO.write(temp,imageType,new File(desFileURI));
}
else if(_height>height&&_width<=width)
{
//scale the source image
tag = new BufferedImage(width,_height,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(org_image,(width-_width)/2,0,_width,_height,null);
//clip image
if(pos.equalsIgnoreCase("TL")||pos.equalsIgnoreCase("TM")||pos.equalsIgnoreCase("TR"))
{
temp = tag.getSubimage(0,0, width,height);
}
else
if(pos.equalsIgnoreCase("ML")||pos.equalsIgnoreCase("MM")||pos.equalsIgnoreCase("MR"))
{
temp = tag.getSubimage(0,(_height-height)/2, width,height);
}
else
{
temp = tag.getSubimage(0,_height-height, width,height);
}
encoder.encode(temp);
//out.close();
ImageIO.write(temp,imageType,new File(desFileURI));
}
else
{
if(_width==_height)
{
if(_width>width)// just scale source image, no clipping.
{
tag = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(org_image,0,0,width,height,null);
encoder.encode(tag);
//out.close();
//ImageIO.write(tag,imageType,new File(desFileURI));
}
}
else if(_width>_height)
{
if(imageType.equals("gif")||imageType.equals("GIF")){
//scale the source image
tag = new
BufferedImage(Math.round((float)_width/_height*height),height,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(org_image,0,0,Math.round((float)_width
/_height*height),height,null);
this.AddError("width","width=
"+Math.round((float)_width/_height*height)+"height="+height);
//clip image
if(pos.equalsIgnoreCase("TL")||pos.equalsIgnoreCase("ML")||pos.equalsIgnoreCase("BL"))
{
temp = tag.getSubimage(0,0, width,height);
}
else
if(pos.equalsIgnoreCase("TM")||pos.equalsIgnoreCase("MM")||pos.equalsIgnoreCase("BM"))
{
temp =
tag.getSubimage(Math.round(((float)_width/_height*height-width)/2),0, width,height);
}
else
{
temp =
tag.getSubimage(Math.round(((float)_width/_height*height-width)),0, width,height);
}
encoder.encode(temp);
//out.close();
//ImageIO.write(temp,imageType,new File(desFileURI));
}
else{
///////scale the image with a high quality//////////
tag = new
BufferedImage(_width,_height,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(org_image,0,0,_width,_height,null);
BufferedImage rtBf = null;
ImageScale is = new ImageScale();
rtBf =
is.imageZoomOut(tag,Math.round((float)_width/_height*height),height);
//this.AddError("width","scale width= "+Math.round((float)_width/_height*height)+" "+"height="+ height);
//clip image
if(pos.equalsIgnoreCase("TL")||pos.equalsIgnoreCase("ML")||pos.equalsIgnoreCase("BL"))
{
temp = rtBf.getSubimage(0,0, width,height);
}
else
if(pos.equalsIgnoreCase("TM")||pos.equalsIgnoreCase("MM")||pos.equalsIgnoreCase("BM"))
{
temp =
rtBf.getSubimage(Math.round(((float)_width/_height*height-width)/2),0, width,height);
}
else
{
temp =
rtBf.getSubimage(Math.round(((float)_width/_height*height-width)),0, width,height);
}
ImageIO.write(temp,imageType,new File(desFileURI));
}
}
else
{
if(imageType.equals("gif")||imageType.equals("GIF")){
//scale the source image
tag = new
BufferedImage(width,Math.round((float)_height/_width*width),BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(org_image,0,0,width,Math.round((float)_height/_width*width),null);
//clip image
if(pos.equalsIgnoreCase("TL")||pos.equalsIgnoreCase("TM")||pos.equalsIgnoreCase("TR"))
{
temp = tag.getSubimage(0,0, width,height);
}
else
if(pos.equalsIgnoreCase("ML")||pos.equalsIgnoreCase("MM")||pos.equalsIgnoreCase("MR"))
{
temp =
tag.getSubimage(0,Math.round(((float)_height/_width*width-height)/2), width,height);
}
else
{
temp =
tag.getSubimage(0,Math.round((float)_height/_width*width-height), width,height);
}
encoder.encode(temp);
// out.close();
//ImageIO.write(temp,imageType,new File(desFileURI));
}
else{
///////scale the image with a high quality//////////
tag = new
BufferedImage(_width,_height,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(org_image,0,0,_width,_height,null);
BufferedImage rtBf = null;
ImageScale is = new ImageScale();
rtBf =
is.imageZoomOut(tag,width,Math.round((float)_height/_width*width));
//clip image
if(pos.equalsIgnoreCase("TL")||pos.equalsIgnoreCase("TM")||pos.equalsIgnoreCase("TR"))
{
temp = rtBf.getSubimage(0,0, width,height);
}
else
if(pos.equalsIgnoreCase("ML")||pos.equalsIgnoreCase("MM")||pos.equalsIgnoreCase("MR"))
{
temp =
rtBf.getSubimage(0,Math.round(((float)_height/_width*width-height)/2), width,height);
}
else
{
temp =
rtBf.getSubimage(0,Math.round((float)_height/_width*width-height), width,height);
}
// encoder.encode(temp);
//out.close();
ImageIO.write(temp,imageType,new File(desFileURI));
}
}
}
out.close();
return "SM"+imageName.substring(2,9);
}
else{
this.AddError("Error","the image format is illegal");
return "fail";
}
}catch(Exception e)
{
this.AddError("Scale Image Fail", e.toString()+" ");
return "fail";
}
}
////inner class for filter and scale image with a high quality.
class ImageScale {
private int width;
private int height;
private int scaleWidth;
double support = (double) 3.0;
double PI = (double) 3.14159265358978;
double[] contrib;
double[] normContrib;
double[] tmpContrib;
int startContrib, stopContrib;
int nDots;
int nHalfDots;
//Use Lanczos filter to replace the original algorithm for image scaling. Lanczos improves
quality of the scaled image
public BufferedImage imageZoomOut(BufferedImage srcBufferImage,int w, int h) {
width = srcBufferImage.getWidth();
height = srcBufferImage.getHeight();
scaleWidth = w;
if (DetermineResultSize(w, h) == 1) {
return srcBufferImage;
}
CalContrib();
BufferedImage pbOut = HorizontalFiltering(srcBufferImage, w);
BufferedImage pbFinalOut = VerticalFiltering(pbOut, h);
return pbFinalOut;
}
/**
* ??????
* */
private int DetermineResultSize(int w, int h) {
double scaleH, scaleV;
scaleH = (double) w / (double) width;
scaleV = (double) h / (double) height;
//??????scaleH?scaleV???????
if (scaleH >= 1.0 && scaleV >= 1.0) {
return 1;
}
return 0;
} // end of DetermineResultSize()
private double Lanczos(int i, int inWidth, int outWidth, double Support) {
double x;
x = (double) i * (double) outWidth / (double) inWidth;
return Math.sin(x * PI) / (x * PI) * Math.sin(x * PI / Support)
/ (x * PI / Support);
} // end of Lanczos()
//
// Assumption: same horizontal and vertical scaling factor
//
private void CalContrib() {
nHalfDots = (int) ((double) width * support / (double) scaleWidth);
nDots = nHalfDots * 2 + 1;
try {
contrib = new double[nDots];
normContrib = new double[nDots];
tmpContrib = new double[nDots];
} catch (Exception e) {
System.out.println("init contrib,normContrib,tmpContrib" + e);
}
int center = nHalfDots;
contrib[center] = 1.0;
double weight = 0.0;
int i = 0;
for (i = 1; i <= center; i++) {
contrib[center + i] = Lanczos(i, width, scaleWidth, support);
weight += contrib[center + i];
}
for (i = center - 1; i >= 0; i--) {
contrib[i] = contrib[center * 2 - i];
}
weight = weight * 2 + 1.0;
for (i = 0; i <= center; i++) {
normContrib[i] = contrib[i] / weight;
}
for (i = center + 1; i < nDots; i++) {
normContrib[i] = normContrib[center * 2 - i];
}
} // end of CalContrib()
//????
private void CalTempContrib(int start, int stop) {
double weight = 0;
int i = 0;
for (i = start; i <= stop; i++) {
weight += contrib[i];
}
for (i = start; i <= stop; i++) {
tmpContrib[i] = contrib[i] / weight;
}
} // end of CalTempContrib()
private int GetRedValue(int rgbValue) {
int temp = rgbValue & 0x00ff0000;
return temp >> 16;
}
private int GetGreenValue(int rgbValue) {
int temp = rgbValue & 0x0000ff00;
return temp >> 8;
}
private int GetBlueValue(int rgbValue) {
return rgbValue & 0x000000ff;
}
private int ComRGB(int redValue, int greenValue, int blueValue) {
return (redValue << 16) + (greenValue << 8) + blueValue;
}
//?????
private int HorizontalFilter(BufferedImage bufImg, int startX, int stopX,
int start, int stop, int y, double[] pContrib) {
double valueRed = 0.0;
double valueGreen = 0.0;
double valueBlue = 0.0;
int valueRGB = 0;
int i, j;
for (i = startX, j = start; i <= stopX; i++, j++) {
valueRGB = bufImg.getRGB(i, y);
valueRed += GetRedValue(valueRGB) * pContrib[j];
valueGreen += GetGreenValue(valueRGB) * pContrib[j];
valueBlue += GetBlueValue(valueRGB) * pContrib[j];
}
valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
Clip((int) valueBlue));
return valueRGB;
} // end of HorizontalFilter()
//??????
private BufferedImage HorizontalFiltering(BufferedImage bufImage, int iOutW) {
int dwInW = bufImage.getWidth();
int dwInH = bufImage.getHeight();
int value = 0;
BufferedImage pbOut = new BufferedImage(iOutW, dwInH,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < iOutW; x++) {
int startX;
int start;
int X = (int) (((double) x) * ((double) dwInW) / ((double) iOutW) + 0.5);
int y = 0;
startX = X - nHalfDots;
if (startX < 0) {
startX = 0;
start = nHalfDots - X;
} else {
start = 0;
}
int stop;
int stopX = X + nHalfDots;
if (stopX > (dwInW - 1)) {
stopX = dwInW - 1;
stop = nHalfDots + (dwInW - 1 - X);
} else {
stop = nHalfDots * 2;
}
if (start > 0 || stop < nDots - 1) {
CalTempContrib(start, stop);
for (y = 0; y < dwInH; y++) {
value = HorizontalFilter(bufImage, startX, stopX, start,
stop, y, tmpContrib);
pbOut.setRGB(x, y, value);
}
} else {
for (y = 0; y < dwInH; y++) {
value = HorizontalFilter(bufImage, startX, stopX, start,
stop, y, normContrib);
pbOut.setRGB(x, y, value);
}
}
}
return pbOut;
} // end of HorizontalFiltering()
private int VerticalFilter(BufferedImage pbInImage, int startY, int stopY,
int start, int stop, int x, double[] pContrib) {
double valueRed = 0.0;
double valueGreen = 0.0;
double valueBlue = 0.0;
int valueRGB = 0;
int i, j;
for (i = startY, j = start; i <= stopY; i++, j++) {
valueRGB = pbInImage.getRGB(x, i);
valueRed += GetRedValue(valueRGB) * pContrib[j];
valueGreen += GetGreenValue(valueRGB) * pContrib[j];
valueBlue += GetBlueValue(valueRGB) * pContrib[j];
// System.out.println(valueRed+"->"+Clip((int)valueRed)+"<-");
//
// System.out.println(valueGreen+"->"+Clip((int)valueGreen)+"<-");
// System.out.println(valueBlue+"->"+Clip((int)valueBlue)+"<-"+"-->");
}
valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
Clip((int) valueBlue));
// System.out.println(valueRGB);
return valueRGB;
} // end of VerticalFilter()
private BufferedImage VerticalFiltering(BufferedImage pbImage, int iOutH) {
int iW = pbImage.getWidth();
int iH = pbImage.getHeight();
int value = 0;
BufferedImage pbOut = new BufferedImage(iW, iOutH,
BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < iOutH; y++) {
int startY;
int start;
int Y = (int) (((double) y) * ((double) iH) / ((double) iOutH) + 0.5);
startY = Y - nHalfDots;
if (startY < 0) {
startY = 0;
start = nHalfDots - Y;
} else {
start = 0;
}
int stop;
int stopY = Y + nHalfDots;
if (stopY > (int) (iH - 1)) {
stopY = iH - 1;
stop = nHalfDots + (iH - 1 - Y);
} else {
stop = nHalfDots * 2;
}
if (start > 0 || stop < nDots - 1) {
CalTempContrib(start, stop);
for (int x = 0; x < iW; x++) {
value = VerticalFilter(pbImage, startY, stopY, start, stop,
x, tmpContrib);
pbOut.setRGB(x, y, value);
}
} else {
for (int x = 0; x < iW; x++) {
value = VerticalFilter(pbImage, startY, stopY, start, stop,
x, normContrib);
pbOut.setRGB(x, y, value);
}
}
}
return pbOut;
} // end of VerticalFiltering()
int Clip(int x) {
if (x < 0)
return 0;
if (x > 255)
return 255;
return x;
}
}
}