此算法,用于生成小于一个范围的缩略图,可以根据需要自由改变。
/**
?? ? * Reads an image in a file and creates a thumbnail in another file.
?? ? * 
?? ? * @param orig
?? ? *??????????? The name of image file.
?? ? * @param thumb
?? ? *??????????? The name of thumbnail file. Will be created if necessary.
?? ? * @param maxDim
?? ? *??????????? The width and height of the thumbnail must be maxDim pixels or
?? ? *??????????? less.
?? ? */
?? ?public void createThumbnail(String orig, String thumb, int maxWidth,int maxHeight,
?? ??? ??? ?int quality,boolean isMax) {
?? ??? ?try {
?? ??? ??? ?// Get the image from a file.
?? ??? ??? ?Image inImage = new ImageIcon(orig).getImage();
?? ??? ??? ?SRC_Height = (double) inImage.getHeight(null);
?? ??? ??? ?SRC_Width = (double) inImage.getWidth(null);
?? ??? ??? ?// System.out.println(SRC_Height + "X" + SRC_Width);
?? ??? ??? ?// Determine the scale.
?? ??? ??? ?double scale = 0.0d;
?? ??? ??? ?double scaleH = (double) maxHeight / (double) inImage.getHeight(null);
?? ??? ??? ?double scaleW = (double) maxWidth / (double) inImage.getWidth(null);
?? ??? ??? ?if(isMax){
?? ??? ??? ??? ?//get the bigger rate,can get the bigger image.? ghj 
?? ??? ??? ??? ?if (scaleH > scaleW) {
?? ??? ??? ??? ??? ?scale = scaleH;
?? ??? ??? ??? ?}else{
?? ??? ??? ??? ??? ?scale = scaleW;
?? ??? ??? ??? ?}?? ?
?? ??? ??? ?}
?? ??? ??? ?else{
?? ??? ??? ??? ?if (scaleH < scaleW) {
?? ??? ??? ??? ??? ?scale = scaleH;
?? ??? ??? ??? ?}else{
?? ??? ??? ??? ??? ?scale = scaleW;
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ??? ?if(scale>1.0)scale? = 1.0;
?? ??? ??? ?// Determine size of new image.
?? ??? ??? ?// One of them
?? ??? ??? ?// should equal maxDim.
?? ??? ??? ?scaledW = (int) (scale * inImage.getWidth(null));
?? ??? ??? ?scaledH = (int) (scale * inImage.getHeight(null));
?? ??? ??? ?// Create an image buffer in
?? ??? ??? ?// which to paint on.
?? ??? ??? ?outImage = new BufferedImage(scaledW, scaledH,
?? ??? ??? ??? ??? ?BufferedImage.TYPE_INT_RGB);
?? ??? ??? ?// Set the scale.
?? ??? ??? ?AffineTransform tx = new AffineTransform();
?? ??? ??? ?// If the image is smaller than
?? ??? ??? ?// the desired image size,
?? ??? ??? ?// don't bother scaling.
?? ??? ??? ?if (scale < 1.0d) {
?? ??? ??? ??? ?tx.scale(scale, scale);
?? ??? ??? ?}
?? ??? ??? ?// Paint image.
?? ??? ??? ?Graphics2D g2d = outImage.createGraphics();
?? ??? ??? ?g2d.drawImage(inImage, tx, null);
?? ??? ??? ?g2d.dispose();
?? ??? ??? ?this.saveAsFile(thumb, outImage, quality);
?? ??? ?} catch (Exception e) {
?? ??? ??? ?e.printStackTrace();
?? ??? ?}
?? ?}
You must be logged in to post a comment.
我喜欢,顶一个!