需要引入jar包
class="java" name="code">
package com.gjw.imagetest;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ImagePress
{
public static void main(String[] args)
{
try
{
File imgageio = new File("C:\\image\\big.jpg");
File imgageout = new File("C:\\image\\big22.png");
dosomething(imgageio,imgageout,50,50);
} catch (FileNotFoundException e)
{
e.printStackTrace();
}catch (IOException e)
{
e.printStackTrace();
}
}
public static boolean dosomething(File imagesrc,File imageout,int min_width,int min_height) throws IOException
{
if (!imagesrc.exists())
{
System.out.println("The original image does not exist!");
return false;
}
Image src = ImageIO.read(imagesrc);
if (src.getWidth(null)==-1)
{
System.out.println("image type problem!");
return false;
}else {
if (src.getWidth(null)>min_width || src.getHeight(null)>min_height)
{
double scale = 0.0;
double w_scale = 0.0;
double h_scale = 0.0;
if (src.getWidth(null)>min_width)
w_scale = min_width/(double)src.getWidth(null);
if (src.getHeight(null)>min_height)
h_scale = min_height/(double)src.getHeight(null);
scale=w_scale<h_scale?w_scale:h_scale;
System.out.println("scaling:="+scale);
if (scale<1)
{
int width = (int) (src.getWidth(null) * scale);
int height = (int) (src.getHeight(null) * scale);
System.out.println("w:"+width);
System.out.println("h:"+height);
/* java提供了4个缩放的微调选项
* image.SCALE_SMOOTH //平滑优先
* image.SCALE_FAST//速度优先
* image.SCALE_AREA_AVERAGING //区域均值
* image.SCALE_REPLICATE //像素复制型缩放
* image.SCALE_DEFAULT //默认缩放模式
* */
BufferedImage bufferedImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR);
bufferedImage.getGraphics().drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH),0, 0, null);
FileOutputStream out = new FileOutputStream(imageout);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode( bufferedImage);
out.close();
System.out.println("photo compression success!");
return true;
}
}
System.out.println("Don't need to compress the images!");
return true;
}
}
}