【问题标题】:URL image to imageview to drawableURL图像到imageview到drawable
【发布时间】:2015-04-09 04:43:05
【问题描述】:
ImageView img1;
    img1 = (ImageView) findViewById (R.id.img1);

        URL newurl = new URL("http://10.0.2.2:80/Gallardo/Practice/files/images/donut.jpg");
        Bitmap mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
        img1.setImageBitmap(mIcon_val);

我从 url 获取图像,但我想将其存储到我的 drawable 中,如何?

【问题讨论】:

标签: android url


【解决方案1】:

apk 中的所有内容都是只读的。 所以你不能写到drawable。

你必须使用“blob”来存储图像。

例如:将图像存储到数据库中

public void insertImg(int id , Bitmap img ) {   


    byte[] data = getBitmapAsByteArray(img); // this is a function

    insertStatement_logo.bindLong(1, id);       
    insertStatement_logo.bindBlob(2, data);

    insertStatement_logo.executeInsert();
    insertStatement_logo.clearBindings() ;

}

 public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 0, outputStream);       
    return outputStream.toByteArray();
}

从数据库中检索图像

public Bitmap getImage(int i){

    String qu = "select img  from table where feedid=" + i ;
    Cursor cur = db.rawQuery(qu, null);

    if (cur.moveToFirst()){
        byte[] imgByte = cur.getBlob(0);
        cur.close();
        return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
    }
    if (cur != null && !cur.isClosed()) {
        cur.close();
    }       

    return null ;
} 

您也可以查看saving image to database

【讨论】:

  • 先生请问这条线是什么? insertStatement_logo.bindLong(1, id); insertStatement_logo.bindBlob(2, 数据); insertStatement_logo.executeInsert(); insertStatement_logo.clearBindings() ;
【解决方案2】:

你可以使用这个constructor构造Drawable:

Drawable drawable = new BitmapDrawable(getResources(), mIcon_val);

您可以像这样将其设置为 ImageView:

img1.setImageDrawable(drawable);

【讨论】:

    【解决方案3】:

    运行 apk 时无法将图像放置在可绘制文件夹中。可以将图像保存到 SD 卡中。

    猜你喜欢
    • 2016-03-02
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多