標籤:android 圖片
上代碼:
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);,如:
【android】把view儲存為圖片的方法以及解決儲存後圖片背景變黑色的問題