以正确的方式从网址加载位图

时间:2015-11-19 09:39:32

标签: java android bitmap

好的家伙需要一些帮助,所以我有一个应用程序从内存创建位图图像并将其显示为图像视图,我按照Android开发人员指南进入这个阶段,因此它具有图像缩放,兑现等等,但现在我想用网站中的图像替换内存中的图像,这是我当前的代码

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,  int reqWidth, int reqHeight){
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

这是我发现从url

制作图像的一些代码
public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    }catch(IOException e){
        e.printStackTrace();
        return null;
    }
}

我想知道如何将这个实现到我现有的代码中,以便将图像缩放到正确的分辨率以适合我的imageView,然后将inJustDecodeBounds设置为true以避免outOfMemory异常或者不再有任何异常需要这样做

1 个答案:

答案 0 :(得分:0)

如果您想在线进行,我建议您使用volley imageLoader,您正在使用的代码正在下载。我会建议你在进入之前进行一些研究,但它与你通常做的有点不同,但是一旦你得到它,图像加载只需要几行。如果你还想下载它,另一个注意事项,将其更改为位图并直接从文件中读取。此外,从存储中显示图像不需要那么多工作,示例位于底部。

http://blog.lemberg.co.uk/volley-part-3-image-loader

 private void loadImageFromStorage(String path, String Name) {
        try {
            File f = new File(path, Name+".jpg");
            double bytes = f.length();
            Bitmap b;
            if(bytes < 1){
                b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
            }
            else{
                b = BitmapFactory.decodeStream(new FileInputStream(f));
            }
            imageView =  (ImageView).findViewById(R.id.grid_image);
            imageView.setImageBitmap(b);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }