转换图像的URL位图快 [英] Converting image url to bitmap quickly

查看:179
本文介绍了转换图像的URL位图快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从API列表中的页面显示图像的列表。对于我使用的两种方法。

第一种方法:结果
  由URL转换为字节数组,然后将其转化成bitmap.Please找到低于code ..

  URL =图片网址新的URL(网址);
URLConnection的UCON = imageUrl.openConnection();InputStream为= ucon.getInputStream();
二BufferedInputStream为=新的BufferedInputStream(是);ByteArrayBuffer BAF =新ByteArrayBuffer(500);
INT电流= 0;
而((电流= bis.read())!= - 1){
     / *这种方法增速放缓的过程中* /
     baf.append((字节)电流);
}字节[] = img_ary baf.toByteArray();

转换字节数组位图:

  ByteArrayInputStream进行的ImageStream =新ByteArrayInputStream的(
                    imgUrl的);
位图theImage = BitmapFactory.de codeStream(的ImageStream);

第二种方法:结果
  根据高度和宽度的图像缩放

 私有静态最后弦乐TAG_iamge =形象;
私有静态最终诠释IO_BUFFER_SIZE = 4 * 1024;公共静态位图loadBitmap(字符串URL){
    位图位图= NULL;
    在的InputStream = NULL;
    的BufferedOutputStream出= NULL;    尝试{
        在=新的BufferedInputStream(新网址(URL).openStream()
                IO_BUFFER_SIZE);        最后ByteArrayOutputStream数据流=新ByteArrayOutputStream();
        OUT =新的BufferedOutputStream(数据流,IO_BUFFER_SIZE);
        副本(IN,OUT);
        了out.flush();        最后一个字节[]数据= dataStream.toByteArray();
        BitmapFactory.Options选项=新BitmapFactory.Options();        options.inJustDe codeBounds = TRUE;
        options.inDither = FALSE;
        options.inPurgeable = TRUE;
        options.inInputShareable = TRUE;        位= BitmapFactory.de codeByteArray的(数据,0,data.length,
                选项​​);        最终诠释身高= options.outHeight;
        最终诠释宽度= options.outWidth;
        INT inSampleSize = 1;
        INT reqHeight = 500;
        INT reqWidth = 500;        如果(高度> reqHeight ||宽度GT; reqWidth){            最终诠释halfHeight =身高/ 2;
            最终诠释半宽度=宽度/ 2;            //计算最大inSampleSize值是2的幂
            //并保持两者
            //高度和宽度大于所请求的高度和宽度。
            而((halfHeight / inSampleSize)GT; reqHeight
                    &功放;&安培; (半角/ inSampleSize)GT; reqWidth){
                inSampleSize * = 2;
            }
        }        int标= inSampleSize;        BitmapFactory.Options O2 =新BitmapFactory.Options();
        o2.inSampleSize =规模;
        o2.inDither = FALSE;
        o2.inPurgeable = TRUE;
        o2.inInputShareable = TRUE;
        返回BitmapFactory.de codeByteArray的(数据,0,data.length,O2);
    }赶上(例外五){
        Log.e(TAG_iamge,无法加载从位图:+网址);
    } {最后
        closeStream(在);
        closeStream(出);
    }    返回位图;
}私有静态无效副本(在的InputStream,OutputStream中出)
        抛出IOException
    字节[] B =新的字节[IO_BUFFER_SIZE]
    INT读;
    而((读取= in.read(二))!= - 1){
        out.write(B,0,读);
    }
}私有静态无效closeStream(可关闭流){
    如果(流!= NULL){
        尝试{
            stream.close();
        }赶上(IOException异常五){
            android.util.Log.e(,无法关闭流,E);
        }
    }
}

两者接近使得APP很慢。因此,这里是我的问题。


  1. 如何快速的URL转换为位图,而不会使应用程序慢?

  2. 如何在其他应用程序(如flipcart)显示图像1000> S,没有任何慢或挂起?

    请指导才能得到答案。



解决方案

有一个名为毕加索库。它可以有效地从URL中加载图像。它也可以从文件加载图像。你想要做的一切,写一行code的。

例如

  Picasso.with(上下文)//上下文
 .load(http://i.imgur.com/DvpvklR.png)// URL / FILE
 .into(ImageView的)//一个ImageView的对象,以显示加载的图像;

它还可以缓存你的形象,所以加载的图像可能是能够更快地加载下一次在不浪费的数据。

有更多的毕加索可用选项。 这里是文档

如果您需要圆角走投无路的位图

  Picasso.with(mContext)
            .load(你的形象,网址或文件,或抽拉)
            .transform(新RoundedTransformation(200,0))
            。适合()
            .into(ImageView的);

RoundedTransformation.java

 进口android.graphics.Bitmap;
进口android.graphics.Bitmap.Config;
进口android.graphics.BitmapShader;
进口android.graphics.Canvas;
进口android.graphics.Paint;
进口android.graphics.RectF;
进口android.graphics.Shader;//实现硬件加速圆角
//这里原来的想法:http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/
公共类RoundedTransformation实现com.squareup.picasso.Transformation {
    私人最终诠释半径;
    私人最终诠释保证金; // DP    //半径为DP圆角半径
    //保证金是DP板
    公共RoundedTransformation(最终诠释半径,最终诠释保证金){
        this.radius =半径;
        this.margin =保证金;
    }    @覆盖
    公共位图转换(最终位图源){
        最终涂料粉刷=新的油漆();
        paint.setAntiAlias​​(真);
        paint.setShader(新BitmapShader(来源Shader.TileMode.CLAMP,Shader.TileMode.CLAMP));        位图输出= Bitmap.createBitmap(source.getWidth(),source.getHeight(),Config.ARGB_8888);
        帆布帆布=新的Canvas(输出);
        canvas.drawRoundRect(新RectF(保证金,保证金,source.getWidth() - 保证金,source.getHeight() - 保证金),半径,半径,油漆);        如果(来源!=输出){
            source.recycle();
        }        返回输出;
    }    @覆盖
    公共字符串键(){
        返回四舍五入;
    }
}

I need to display the list of images from api in the list page. For that i used two approaches.

First Approach:
By converting the url to byte array and then converting it into bitmap.Please find the below code..

URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();

InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);

ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
     /* This approach slowdown the process*/
     baf.append((byte) current);
}

byte[] img_ary= baf.toByteArray();

Converting byte array to bitmap:

ByteArrayInputStream imageStream = new ByteArrayInputStream(
                    imgUrl);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);

Second Approach:
Image scaling based on height and width

private static final String TAG_iamge = "Image";
private static final int IO_BUFFER_SIZE = 4 * 1024;

public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(),
                IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inJustDecodeBounds = true;
        options.inDither = false;
        options.inPurgeable = true;
        options.inInputShareable = true;

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

        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        int reqHeight = 500;
        int reqWidth = 500;

        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;
            }
        }

        int scale = inSampleSize;

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        o2.inDither = false;
        o2.inPurgeable = true;
        o2.inInputShareable = true;
        return BitmapFactory.decodeByteArray(data, 0, data.length, o2);
    } catch (Exception e) {
        Log.e(TAG_iamge, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }

    return bitmap;
}

private static void copy(InputStream in, OutputStream out)
        throws IOException {
    byte[] b = new byte[IO_BUFFER_SIZE];
    int read;
    while ((read = in.read(b)) != -1) {
        out.write(b, 0, read);
    }
}

private static void closeStream(Closeable stream) {
    if (stream != null) {
        try {
            stream.close();
        } catch (IOException e) {
            android.util.Log.e("", "Could not close stream", e);
        }
    }
}

Both approaches making the APP very slow. So here is my questions..

  1. How can i quickly convert the url into bitmap without making the app slow?
  2. How the other apps(like flipcart) displaying the 1000>s of images, without any slow or hang?

    Please guide to get the answer.

解决方案

There is a library named Picasso. which can efficiently load images from url. it can also load image from the File. all you wanted to do , write a line of code.

example

Picasso.with(context) //Context
 .load("http://i.imgur.com/DvpvklR.png") //URL/FILE
 .into(imageView)//an ImageView Object to show the loaded image; 

It can also cache your image, so the loaded image could be able to load faster on the next time without wasting the data.

There are many more options available in Picasso. Here is the documentation

If you need rounded cornered bitmap

    Picasso.with(mContext)
            .load("your-image-url-or-file-or-drawable")
            .transform(new RoundedTransformation(200, 0))
            .fit()
            .into(imageView);

RoundedTransformation.java

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;

// enables hardware accelerated rounded corners
// original idea here : http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/
public class RoundedTransformation implements com.squareup.picasso.Transformation {
    private final int radius;
    private final int margin;  // dp

    // radius is corner radii in dp
    // margin is the board in dp
    public RoundedTransformation(final int radius, final int margin) {
        this.radius = radius;
        this.margin = margin;
    }

    @Override
    public Bitmap transform(final Bitmap source) {
        final Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));

        Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        canvas.drawRoundRect(new RectF(margin, margin, source.getWidth() - margin, source.getHeight() - margin), radius, radius, paint);

        if (source != output) {
            source.recycle();
        }

        return output;
    }

    @Override
    public String key() {
        return "rounded";
    }
}

这篇关于转换图像的URL位图快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆