在Android中将字符串转换为图像?

时间:2015-03-30 08:22:13

标签: android string bitmap imageview

所以,这就是事情。我通过WebService接收了一个imagepath。我将imagepath存储在String中。现在我想将String转换为Bitmap并在imageView中显示图像。我尝试了互联网上的例子中的许多代码但是没有工作。

尝试1:

      Bitmap bm = BitmapFactory.decodeFile(imagelogo);
      imageView2 = (ImageView) findViewById(R.id.imageView2);
      imageView2.setImageBitmap(bm);

尝试2:首先我将String转换为字符串Base64,然后将Base64字符串转换为Bitmap。

     byte[] data;
     String base64;
      {
       try {
          data = imagelogo.getBytes("UTF-8");
          String base64 = Base64.encodeToString(data, Base64.DEFAULT);
          Log.i("Base 64 ", base64);
          } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
          }
      }

      public Bitmap StringToBitMap(String encodedString){
       try {
          byte [] encodeByte=Base64.decode(base64 ,Base64.DEFAULT);
          Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
          return bitmap;
       } catch(Exception e) {
          e.getMessage();
          return null;
       }
    }          

任何帮助将不胜感激。提前谢谢。

2 个答案:

答案 0 :(得分:1)

天啊,你不能将一串图像路径转换为位图!图像路径不是图像本身! 您需要通过图片路径从互联网下载图片并将其存储到本地文件。你需要称之为:

Bitmap bm = BitmapFactory.decodeFile(localImagePath);

加载图片。

答案 1 :(得分:1)

使用此链接:

http://www.androidhive.info/2012/07/android-loading-image-from-url-http/

非常简单,然后使用此代码:

int loader = R.drawable.loader;

    // Imageview to show
    ImageView image = (ImageView) findViewById(R.id.image);

    // Image url
    String image_url = "http://api.androidhive.info/images/sample.jpg";

    // ImageLoader class instance
    ImageLoader imgLoader = new ImageLoader(getApplicationContext());

    // whenever you want to load an image from url
    // call DisplayImage function
    // url - image url to load
    // loader - loader image, will be displayed before getting image
    // image - ImageView
    imgLoader.DisplayImage(image_url, loader, image);

希望它会帮助你......