上代码:
public class MainActivity extends Activity { ImageView imgView; @Override protected 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);,如下图:
时间: 2024-10-16 17:24:24