java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

JAVA缩略图算法

此算法,用于生成小于一个范围的缩略图,可以根据需要自由改变。

/**
?? ? * 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();
?? ??? ?}
?? ?}



This entry was posted in JAVA and tagged . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-img-suo/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

One Response to JAVA缩略图算法

  1. Annie says:

    我喜欢,顶一个!

Leave a Reply