【问题标题】:Convert String to Image in Android?在Android中将字符串转换为图像?
【发布时间】:2015-03-30 08:22:12
【问题描述】:

所以,事情就是这样。我正在通过 WebService 接收图像路径。我将图像路径存储在字符串中。现在我想将字符串转换为位图并在 imageView 中显示图像。我尝试了互联网上示例中的许多代码,但都无法正常工作。

尝试1:

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

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

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

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

【问题讨论】:

  • 如果你有图片的 url 并且想在ImageView 中显示它,那么只需使用毕加索库square.github.io/picasso
  • 好的。谢谢你,M-WaJeEh。这是一个简单而好主意。
  • 你为什么使用imagelogo.getBytes("UTF-8");?您的字符串可能不是 UTF-8 编码的。
  • 您遇到的错误或异常是什么?

标签: android string bitmap imageview


【解决方案1】:

天哪,你不能将图像路径字符串转换为位图!图像路径不是图像本身! 您需要通过图片路径从互联网下载图片并保存到本地文件中。你需要这样称呼:

Bitmap bm = BitmapFactory.decodeFile(localImagePath);

加载图像。

【讨论】:

  • 您不需要将其存储在文件中。
  • @weston 是的,确实如此。我只是试图告诉发帖者链接到服务器的图像路径和链接到本地​​存储系统的图像路径之间的区别。
  • 是的,我明白了,但请记住,他们会从字面上理解您所写的内容。他们将查找如何下载和存储在文件中,然后将该文件放在 android 中的哪个位置,他们将添加文件系统权限,他们根本不需要走那条路。
【解决方案2】:

使用此链接:

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

希望对你有所帮助..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多