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

java异步上传图片示例

程序员文章站 2024-02-23 23:48:22
复制代码 代码如下:final file imagefile = new file(getcachedir().getpath() + "/img/" + p.image)...

复制代码 代码如下:

final file imagefile = new file(getcachedir().getpath() + "/img/" + p.image);
image.setvisibility(view.gone);
view.findviewbyid(r.id.imageloading).setvisibility(view.visible);
(new asynctask<void, void, bitmap>() {
    @override
    protected bitmap doinbackground(void... params) {
        try {
            bitmap image;
            if (!imagefile.exists() || imagefile.length() == 0) {
                image = bitmapfactory.decodestream(new url(
                        "http://example.com/images/"
                                + p.image).openstream());
                image.compress(bitmap.compressformat.jpeg, 85,
                        new fileoutputstream(imagefile));
                image.recycle();
            }
            image = bitmapfactory.decodefile(imagefile.getpath(),
                bitmapoptions);
            return image;
        } catch (malformedurlexception ex) {
            // todo auto-generated catch block
            ex.printstacktrace();
            return null;
        } catch (ioexception ex) {
            // todo auto-generated catch block
            ex.printstacktrace();
            return null;
        }
    }

    @override
    protected void onpostexecute(bitmap image) {
        if (view.gettag() != p) // the view was recycled.
            return;
            view.findviewbyid(r.id.imageloading).setvisibility(
                view.gone);
        view.findviewbyid(r.id.image)
                .setvisibility(view.visible);
        ((imageview) view.findviewbyid(r.id.image))
                .setimagebitmap(image);
    }
}).execute();