上代码:

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


activity_main.xml:

<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);,如下图:




更多相关文章

  1. 适配 Android10 内部存储图片显示问题
  2. Android 自定义通知Notification 适配不同背景颜色
  3. 图片旋转的两种方法
  4. Android 使用颜色矩阵改变图片颜色,透明度,亮度
  5. android 显示gif格式的图片
  6. 在 Android 开发中使用协程 | 背景介绍
  7. 详细讲解Android的图片下载框架UniversialImageLoader之磁盘缓存
  8. OOM的出现及解决(加载图片)

随机推荐

  1. Android实现朋友圈多图显示功能
  2. Android(安卓)客户端将位置信息发送给服
  3. Android(安卓)开发学习中 各种问题收集
  4. Android系统框架概述
  5. JS与Android(安卓)交互
  6. AndroiManifest.xml文件中android属性
  7. Android(安卓)EditText的设置以及软键盘
  8. 如何去掉Android(安卓)studio 顶部状态栏
  9. Android(安卓)Service总结06 之AIDL
  10. Android之TextView属性大全