java 生成缩略图(四种生成方法)

作者:简简单单 2010-08-30


<%@ page contenttype="text/html; charset=gb2312" language="java" import="java.sql.*" errorpage="" %>




java 生成缩略图(四种生成方法)


<%
//方法一

image src = toolkit.gettoolkit.createimage;
然后先生成一个bufferedimage bi作为画布.
bufferedimage bi = new bufferedimage(目标宽, 目标高,bufferedimage.type_int_rgb);
得到它的graphics对象:
graphics g = bi.getgraphics;
然后往这个画而上画原图就行了:
g.grawimage;
找一个编码类,如jpegencoder,gifencoder
把bi编码输出就行了.


//方法二

将图按比例缩小。
     public static bufferedimage resize(bufferedimage source, int targetw, int targeth) {
         // targetw,targeth分别表示目标长和宽
         int type = source.gettype();
         bufferedimage target = null;
         double sx = (double) targetw / source.getwidth();
         double sy = (double) targeth / source.getheight();
         //这里想实现在targetw,targeth范围内实现等比缩放。如果不需要等比缩放
         //则将下面的if else语句注释即可
         if(sx>sy)
         {
             sx = sy;
             targetw = (int)(sx * source.getwidth());
         }else{
             sy = sx;
             targeth = (int)(sy * source.getheight());
         }
         if (type == bufferedimage.type_custom) { //handmade
             colormodel cm = source.getcolormodel();
             writableraster raster = cm.createcompatiblewritableraster(targetw, targeth);
             boolean alphapremultiplied = cm.isalphapremultiplied();
             target = new bufferedimage(cm, raster, alphapremultiplied, null);
         } else
             target = new bufferedimage(targetw, targeth, type);
             graphics2d g = target.creategraphics();
             //smoother than exlax:
             g.setrenderinghint(renderinghints.key_rendering, renderinghints.value_render_quality );
             g.drawrenderedimage(source, affinetransform.getscaleinstance(sx, sy));
             g.dispose();
             return target;
         }
    
         public static void saveimageasjpg (string fromfilestr,string savetofilestr,int width,int hight)
         throws exception {
         bufferedimage srcimage;
         // string ex = fromfilestr.substring(fromfilestr.indexof("."),fromfilestr.length());
         string imgtype = "jpeg";
         if (fromfilestr.tolowercase().endswith(".png")) {
             imgtype = "png";
         }
         // system.out.println(ex);
         file savefile=new file(savetofilestr);
         file fromfile=new file(fromfilestr);
         srcimage = imageio.read(fromfile);
         if(width > 0 || hight > 0)
         {
             srcimage = resize(srcimage, width, hight);
         }
         imageio.write(srcimage, imgtype, savefile);

     }
    
     public static void main (string argv[]) {
         try{
         //参数1(from),参数2(to),参数3(宽),参数4(高)
             saveimageasjpg("c:\documents and settings\www.111com.net\www.111com.net\tmr-06.jpg",
                     "c:\documents and settings\www.111com.net\www.111com.net\2.jpg",
                     120,120);
         } catch(exception e){
             e.printstacktrace();
         }

     }

 
//方法三

import javax.imageio.imageio;
import javax.imageio.iioexception;
import java.awt.image.bufferedimage;
import java.awt.image;
import java.io.file;
import java.awt.image.affinetransformop;
import java.awt.geom.affinetransform;

public class test

double sx = nw / w;
double sy = nh / h;

transform.settoscale;

affinetransformop ato = new affinetransformop;
bufferedimage bid = new bufferedimage;
ato.filter;
imageio.write;
} catch
}
}

//方法四

import java.awt.image;
import java.awt.toolkit;
import java.awt.image.bufferedimage;
import java.awt.image.memoryimagesource;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;

import javax.imageio.imageio;

import com.sun.image.codec.jpeg.jpegcodec;
import com.sun.image.codec.jpeg.jpegimageencoder;

/** *//**
 * @author liuwei
 *
 */
public class imagehelper ...{

    private static final string bmp = "bmp";
    private static final string png = "png";
    private static final string gif = "gif";
    private static final string jpeg = "jpeg";
    private static final string jpg = "jpg";
    public static final string thumbnail = "thumbnail.jpg";

    public static void zoompicture(
            string source,
            int width,
            int height,
            boolean adjustsize) ...{
        if (source == null || source.equals("") || width < 1 || height < 1) ...{
            return;
        }
        source = source.tolowercase();
        if (source.endswith(bmp)) ...{
            bmpthumbnailhandler(source, width, height, adjustsize);
        } else if (source.endswith(png) || source.endswith(gif)
                || source.endswith(jpeg) || source.endswith(jpg)) ...{
            thumbnailhandler(source, width, height, adjustsize);
        }
    }

    private static void thumbnailhandler(
            string source,
            int width,
            int height,
            boolean adjustsize) ...{
        try ...{
            file sourcefile = new file(source);
            if (sourcefile.exists()) ...{
                image image = imageio.read(sourcefile);
                int theimgwidth = image.getwidth(null);
                int theimgheight = image.getheight(null);
                int[] size = ...{ theimgwidth, theimgheight };
                if (adjustsize) ...{
                    size = adjustimagesize(theimgwidth, theimgheight, width,height);
                }
                stringbuffer thumbnailfile=new stringbuffer();
                thumbnailfile.append(sourcefile.getparent());
                thumbnailfile.append(file.separatorchar);
                thumbnailfile.append(thumbnail);
                writefile(image, size[0], size[1], thumbnailfile.tostring());
            }
        } catch (exception e) ...{
            e.printstacktrace();
            return;
        }
    }

    private static void bmpthumbnailhandler(
            string source,
            int width,
            int height,
            boolean adjustsize) ...{
        try ...{
            file sourcefile = new file(source);
            if (sourcefile.exists()) ...{
                image image = getbmpimage(source);
                int theimgwidth = image.getwidth(null);
                int theimgheight = image.getheight(null);
                int[] size = ...{ theimgwidth, theimgheight };
                if (adjustsize) ...{
                    size = adjustimagesize(theimgwidth, theimgheight, width, height);
                }
                stringbuffer thumbnailfile=new stringbuffer();
                thumbnailfile.append(sourcefile.getparent());
                thumbnailfile.append(file.separatorchar);
                thumbnailfile.append(thumbnail);
                writefile(image, size[0], size[1], thumbnailfile.tostring());
            }
        } catch (exception e) ...{
            e.printstacktrace();
            return;
        }
    }

    private static image getbmpimage(string source) throws exception ...{

        fileinputstream fs = null;
        image image = null;
        try ...{
            fs = new fileinputstream(source);
            int bflen = 14;
            byte bf[] = new byte[bflen];
            fs.read(bf, 0, bflen); // 读取14字节bmp文件头
            int bilen = 40;
            byte bi[] = new byte[bilen];
            fs.read(bi, 0, bilen); // 读取40字节bmp信息头

            // 源图宽度
            int nwidth = (((int) bi[7] & 0xff) << 24)
                    | (((int) bi[6] & 0xff) << 16)
                    | (((int) bi[5] & 0xff) << 8) | (int) bi[4] & 0xff;

            // 源图高度
            int nheight = (((int) bi[11] & 0xff) << 24)
                    | (((int) bi[10] & 0xff) << 16)
                    | (((int) bi[9] & 0xff) << 8) | (int) bi[8] & 0xff;

            // 位数
            int nbitcount = (((int) bi[15] & 0xff) << 8) | (int) bi[14] & 0xff;

            // 源图大小
            int nsizeimage = (((int) bi[23] & 0xff) << 24)
                    | (((int) bi[22] & 0xff) << 16)
                    | (((int) bi[21] & 0xff) << 8) | (int) bi[20] & 0xff;

            // 对24位bmp进行解析
            if (nbitcount == 24) ...{
                int npad = (nsizeimage / nheight) - nwidth * 3;
                int ndata[] = new int[nheight * nwidth];
                byte brgb[] = new byte[(nwidth + npad) * 3 * nheight];
                fs.read(brgb, 0, (nwidth + npad) * 3 * nheight);
                int nindex = 0;
                for (int j = 0; j < nheight; j++) ...{
                    for (int i = 0; i < nwidth; i++) ...{
                        ndata[nwidth * (nheight - j - 1) + i] = (255 & 0xff) << 24
                                | (((int) brgb[nindex + 2] & 0xff) << 16)
                                | (((int) brgb[nindex + 1] & 0xff) << 8)
                                | (int) brgb[nindex] & 0xff;
                        nindex += 3;
                    }
                    nindex += npad;
                }
                toolkit kit = toolkit.getdefaulttoolkit();
                image = kit.createimage(new memoryimagesource(nwidth, nheight,
                        ndata, 0, nwidth));
            }
        } catch (exception e) ...{
            e.printstacktrace();
            throw new exception(e);
        } finally ...{
            if (fs != null) ...{
                fs.close();
            }
        }
        return image;
    }

    private static void writefile(
            image image,
            int width,
            int height,
            string thumbnailfile) throws exception ...{
       
        if (image == null) return;
       
        bufferedimage tag = new bufferedimage(width, height,bufferedimage.type_int_rgb);
        tag.getgraphics().drawimage(image, 0, 0, width, height, null);
        fileoutputstream out = null;
        try ...{
            out = new fileoutputstream(thumbnailfile);
            jpegimageencoder encoder = jpegcodec.createjpegencoder(out);
            encoder.encode(tag);
        } catch (exception e) ...{
            e.printstacktrace();
            throw new exception(e);
        } finally ...{
            if (out != null) ...{
                out.close();
            }
        }

    }

    private static int[] adjustimagesize(int theimgwidth, int theimgheight,
            int defwidth, int defheight) ...{       
        int[] size = ...{ 0, 0 };
       
        float theimgheightfloat=float.parsefloat(string.valueof(theimgheight));
        float theimgwidthfloat=float.parsefloat(string.valueof(theimgwidth));
        if (theimgwidth             float scale=theimgheightfloat/theimgwidthfloat;
            size[0]=math.round(defheight/scale);
            size[1]=defheight;
        }else...{
            float scale=theimgwidthfloat/theimgheightfloat;
            size[0]=defwidth;
            size[1]=math.round(defwidth/scale);
        }
        return size;
    }

    public static void main(string[] agrs) ...{
        zoompicture("f:www.111com.net过年dscf1042.jpg", 80, 80, true);
    }

}

%>

相关文章

精彩推荐