【问题标题】:How to load an ImageView with a png file without using "setImageBitmap()"?如何在不使用“setImageBitmap()”的情况下加载带有 png 文件的 ImageView?
【发布时间】:2012-08-11 20:14:42
【问题描述】:

我对@9​​87654321@ 对象进行一些处理(质量改进和一些调整大小),然后使用bitmap.compress() 函数通过提供文件名“myfile.png”来存储它。

newbitmap = processImage(bitmap);
FileOutputStream fos = context.openFileOutput("myfile.png", Context.MODE_PRIVATE);
newbitmap.compress(CompressFormat.PNG, 100, fos);

现在我想在ImageView 中加载此图像,但我不能使用setImageBitmap() 来执行此操作。有没有其他选择?

我不能使用setImageBitmap()的原因是我将RemoteViews用于小部件,并且使用位图方法在图像很大时会导致Binder Transaction失败错误。

我尝试使用下面的代码设置图像 uri,但图像无法在 ImageView 上加载:

RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

File internalFile = context.getFileStreamPath("myfile.png");
Uri internal = Uri.fromFile(internalFile);
rv.setImageViewUri(R.id.widgetImageView, internal);
updateAppWidget(awID, rv);

感谢您的帮助!

【问题讨论】:

  • 有什么方法可以发送字节数组吗?然后从另一侧解码位图。我不确定。

标签: android android-imageview android-file


【解决方案1】:

在内部存储中存储图像时,您必须将模式设置为MODE_WORLD_READABLE 而不是MODE_PRIVATE。这是因为小部件由主屏幕进程处理,如果您不正确设置模式,它就无法访问您的文件。

所以替换这一行:

FileOutputStream fos = context.openFileOutput("myfile.png", Context.MODE_PRIVATE);

与:

FileOutputStream fos = context.openFileOutput("myfile.png", Context.MODE_WORLD_READABLE);

另外,使用Uri.parse()getPath() 代替fromFile()fromFile() 仅适用于 Android 2.2 及更高版本。

Uri internal = Uri.Parse(internalFile.getPath());

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    使用rv.setUri(R.id.widgetImageView, "setImageURI", "file://myfile.png"); 而不是rv.setImageViewUri(R.id.widgetImageView, internal); 似乎可以正确加载图像。您可能想尝试一下。

    如果这不起作用,仍然可以选择缩小图像,以便您可以使用setImageBitmap 方法。 示例:

     public static Bitmap scaleDownBitmap(Bitmap photo, int newHeight, Context context) {
    
     final float densityMultiplier = context.getResources().getDisplayMetrics().density;        
    
     int h= (int) (newHeight*densityMultiplier);
     int w= (int) (h * photo.getWidth()/((double) photo.getHeight()));
    
     photo=Bitmap.createScaledBitmap(photo, w, h, true);
    
     return photo;
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2010-10-18
      • 2015-03-24
      相关资源
      最近更新 更多