2 u010539040 u010539040 于 2014.05.07 16:22 提问

android下载图片保存到本地图片大小为0KB,是什么原因??求大神解决

public Drawable loadImageFromUrl(String urlPath, String directory,
String filename) {
byte[] data = null;
InputStream is = null;
Drawable drawable = null;
HttpURLConnection conn = null;
URL url = null;
try {
url = new URL(urlPath);
} catch (Exception e) {
e.printStackTrace();
return drawable;
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
// conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);
is = conn.getInputStream();
if (conn.getResponseCode() == 200) {
BitmapFactory.Options opts = new BitmapFactory.Options();
data = readInputStream(is);
//处理图片溢出
opts.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, opts);
opts.inSampleSize = computeSampleSize(opts, -1, AppContext.getScreenHeight()*AppContext.getScreenWidth());
opts.inJustDecodeBounds = false;

            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
                    data.length, opts);

            drawable = (Drawable) new BitmapDrawable(bitmap);
            // 如果目录和图片名称存在,保存图片
            if (null != directory && null != filename) {
                // 创建目录,保存图片
                if (hasStorage(true, directory)) {
                    // 目录地址
                    String directoryName = SDPATH + directory;
                    // 创建文件
                    File file = new File(directoryName, filename);

                    BufferedOutputStream bos = new BufferedOutputStream(
                            new FileOutputStream(file));

                    // 获取图片的格式
                    String dat = filename.substring(filename
                            .lastIndexOf(".") + 1);
                    Log.d(TAG, "图片格式1111111111:" + dat);
                    if ("jpg".equals(dat)) {
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos);
                    } else if ("png".equals(dat)) {
                        bitmap.compress(Bitmap.CompressFormat.PNG, 90, bos);
                    }

                    bos.flush();
                    bos.close();
                } else {
                    Log.d(TAG, "save picture failed");
                }
            }

        } else {
            data = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        drawable = null;
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        conn.disconnect();
    }

    return drawable;
}

1个回答

icyblood198999
icyblood198999   Rxr 2014.05.09 14:03

0k的话,主要还是考虑请求没有成功,图片根本没有传到android端的情况

Csdn user default icon
上传中...
上传图片
插入图片