欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java根据url抓取并生成缩略图的示例

程序员文章站 2024-03-31 13:55:04
java根据url抓取并生成缩略图复制代码 代码如下:public static bitmap loadimagefromurl(string url, int sc) {...

java根据url抓取并生成缩略图

复制代码 代码如下:

public static bitmap loadimagefromurl(string url, int sc) {
        url m;
        inputstream i = null;
        bufferedinputstream bis = null;
        bytearrayoutputstream out = null;
        byte isbuffer[] = new byte[1024];
        if (url == null)
            return null;
        try {
            m = new url(url);
            i = (inputstream) m.getcontent();

            bis = new bufferedinputstream(i, 1024 * 4);
            out = new bytearrayoutputstream();
            int len = 0;
            while ((len = bis.read(isbuffer)) != -1) {
                out.write(isbuffer, 0, len);
            }
            out.close();
            bis.close();
        } catch (malformedurlexception e1) {
            e1.printstacktrace();
            return null;
        } catch (ioexception e) {
            e.printstacktrace();
        }
        if (out == null)
            return null;
        byte[] data = out.tobytearray();
        bitmapfactory.options options = new bitmapfactory.options();
        options.injustdecodebounds = true;
        bitmapfactory.decodebytearray(data, 0, data.length, options);
        options.injustdecodebounds = false;
        int be = (int) (options.outheight / (float) sc);
        if (be <= 0) {
            be = 1;
        } else if (be > 3) {
            be = 3;
        }
        options.insamplesize = be;
        bitmap bmp = null;
        try {
            bmp = bitmapfactory.decodebytearray(data, 0, data.length, options); // 返回缩略图
        } catch (outofmemoryerror e) {
            // todo: handle exception
            system.gc();
            bmp = null;
        }
        return bmp;
    }