import javaawtContainer;
import javaawtDimension;
import javaawtGraphicsD;
import javaawtImage;
import javaawtMediaTracker;
import javaawtRectangle;
import javaawtRenderingHints;
import javaawtRobot;
import javaawtToolkit;
import javaawtimageBufferedImage;
import javaioBufferedOutputStream;
import javaioFile;
import javaioFileOutputStream;
import javaximageioImageIO;
import decjpegJPEGCodec;
import decjpegJPEGEncodeParam;
import decjpegJPEGImageEncoder;
/**
*
* 纯java API实现图片处理
* <p>Title:ImageChangeSize</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) </p>
* <p>Company: </p>
* @author
* @version
*/
public class ImageChangeSize
{
public static void main ( String [] args )
throws InterruptedException
{
//测试生成缩略图
createThumbnail(c:\\gif c:\\uuuujpg);
//测试捕捉屏幕每隔一秒捕获一次
String path = c:\\screen\\;
int i = ;
for ( ;; )
{
i++;
String filepath = path + i + jpg;
snatchScreen(filepath);
ThreadcurrentThread()sleep();
}
}
/**
* 处理图片改变起大小可进行缩略和放大
* @param filename 源文件名称
* @param thumbWidth 处理后宽度
* @param thumbHeight 处理后高度
* @param quality 品质 最高最小
* @param outFilename 输出文件名称
*/
public static void createThumbnail ( String filename int thumbWidth int thumbHeight int quality String outFilename )
{
Image image = ToolkitgetDefaultToolkit()getImage(filename);
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTrackeraddImage(image );
try
{
mediaTrackerwaitForID();
double thumbRatio = (double) thumbWidth / (double) thumbHeight;
int imageWidth = imagegetWidth(null);
int imageHeight = imagegetHeight(null);
double imageRatio = (double) imageWidth / (double) imageHeight;
if ( thumbRatio < imageRatio )
{
thumbHeight = (int) ( thumbWidth / imageRatio );
}
else
{
thumbWidth = (int) ( thumbHeight * imageRatio );
}
BufferedImage thumbImage = new BufferedImage(thumbWidth
thumbHeight BufferedImageTYPE_INT_RGB);
GraphicsD graphicsD = thumbImagecreateGraphics();
graphicsDsetRenderingHint(RenderingHintsKEY_INTERPOLATION RenderingHintsVALUE_INTERPOLATION_BILINEAR);
graphicsDdrawImage(image thumbWidth thumbHeight null);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
JPEGImageEncoder encoder = JPEGCodeccreateJPEGEncoder(out);
JPEGEncodeParam param = encodergetDefaultJPEGEncodeParam(thumbImage);
quality = Mathmax( Mathmin(quality ));
paramsetQuality((float) quality / f false);
encodersetJPEGEncodeParam(param);
encoderencode(thumbImage);
outclose();
}
catch ( Exception e )
{
eprintStackTrace();
}
}
/**
* 抓取电脑屏幕
* @param path
*/
public static void snatchScreen ( String path )
{
Robot robot;
try
{
robot = new Robot();
Dimension d = ToolkitgetDefaultToolkit()getScreenSize();
Rectangle rect = new Rectangle( dwidth dheight);
BufferedImage image = robotcreateScreenCapture(rect);
ImageIOwrite(image jpg new File(path));
}
catch ( Exception e )
{
Systemoutprintln(Failed to snatch screen );
eprintStackTrace();
}
}
}