【android】把view保存为图片的方法以及解决保存后图片背景变黑色的问题
16lz
2021-01-23
上代码:
public class MainActivity extends Activity {ImageView imgView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imgView = (ImageView) findViewById(R.id.imageView);imgView.setDrawingCacheEnabled(true);// this is the important code :) // Without it the view will have a dimension of 0,0 and the bitmap will be null imgView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));imgView.layout(0, 0, imgView.getMeasuredWidth(), imgView.getMeasuredHeight()); Bitmap bitmap = Bitmap.createBitmap(imgView.getDrawingCache());imgView.setDrawingCacheEnabled(false);String strPath ="/testSaveView/"+UUID.randomUUID().toString()+".png";if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File sdCardDir=Environment.getExternalStorageDirectory(); FileOutputStream fos = null; try{ File file = new File(sdCardDir,strPath); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } fos = new FileOutputStream(file); //当指定压缩格式为PNG时保存下来的图片显示正常 bitmap.compress(CompressFormat.JPEG, 100, fos); //当指定压缩格式为JPEG时保存下来的图片背景为黑色// bitmap.compress(CompressFormat.JPEG, 100, fos); fos.flush(); }catch(Exception e){ e.printStackTrace(); }finally{ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }}}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ImageView android:id="@+id/imageView" android:layout_width="100dp" android:layout_height="100dp" android:scaleType="centerInside" android:src="@drawable/ic_launcher"/></LinearLayout>
需要注意两个问题:
一、调用getDrawingCache()前先要测量,否则的话得到的bitmap为null,这个我在OnCreate()、OnStart()、OnResume()方法里都试验过。
二、当调用bitmap.compress(CompressFormat.JPEG, 100, fos);保存为图片时发现图片背景为黑色,如下图:
这时只需要改成用png保存就可以了,bitmap.compress(CompressFormat.PNG, 100, fos);,如下图:
更多相关文章
- 适配 Android10 内部存储图片显示问题
- Android 自定义通知Notification 适配不同背景颜色
- 图片旋转的两种方法
- Android 使用颜色矩阵改变图片颜色,透明度,亮度
- android 显示gif格式的图片
- 在 Android 开发中使用协程 | 背景介绍
- 详细讲解Android的图片下载框架UniversialImageLoader之磁盘缓存
- OOM的出现及解决(加载图片)