将图像URL转换为位图,有时在标记中使用时显示内存不足错误



>我在应用程序中使用地图,所以我正在自定义地图中的标记。当我直接给图像 url 时,应用程序打开时它不会显示,所以我正在转换为位图。 有时应用程序崩溃。我引用了很多链接,但我没有得到正确的代码。

问题:

致命异常:java.lang.OutOfMemoryError 无法分配具有 4194208 个可用字节和 17MB 的 55987212 字节分配,直到 OOM

致命异常:java.lang.OutOfMemoryError at android.graphics.BitmapFactory.nativeDecodeStream(BitmapFactory.java(

法典:

try {
URL url = new URL("http://default-environment.8ed3pmbznb.ap-south-1.elasticbeanstalk.com/images/profile/2018-04-03-14-01-022017-11-13-07-12-36Image.jpg");
Bitmap  bitmapimage = BitmapFactory.decodeStream(url.openConnection().getInputStream());
Bitmap scaled = Bitmap.createScaledBitmap(bitmapimage, 100, 100, true);
//scaled = BitmapFactory.decodeFile(ServerUtils.Gs_ImagePath+gs_var_user_image);
}
catch(IOException e) {
System.out.println(e);
}

在标记中设置图像:

LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.fromBitmap(drawableToIcon(getContext(),scaled, Is_active)));
mMap.addMarker(mMarker);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));

自定义布局中的标记

public  Bitmap drawableToIcon(@NonNull Context context, Bitmap image, String status) {

View marker = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_layout, null);
ImageView rlay = (ImageView) marker.findViewById(R.id.imageView1);
markerImage.setImageBitmap(image);
marker.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
marker.layout(0, 0, marker.getMeasuredWidth(), marker.getMeasuredHeight());
marker.buildDrawingCache();
Bitmap returnedBitmap = Bitmap.createBitmap(marker.getMeasuredWidth(), marker.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
Drawable drawable = marker.getBackground();
if (drawable != null)
drawable.draw(canvas);
marker.draw(canvas);
return returnedBitmap;
}

如果我将图像网址直接设置为标记,第一次不会加载,刷新页面时仅显示我将其转换为位图。即使我也使用它减小了位图大小

createScaledBitmap(bitmapimage, 100, 100, true);

任何人都可以回复我

Bitmap scaled = Bitmap.createScaledBitmap(bitmapimage, 100, 100, true(;

这是错误的方法,因为在您创建已经导致 oom 的大位图"bimapimage"之前。

相反,您应该将decodeStream与缩放选项参数一起使用,以便直接获得一个小位图。

相关内容

最新更新