为什么我在Android中保存图像时会出现黑色背景

时间:2014-04-03 08:16:22

标签: android android-bitmap

我将总相对布局保存为位图。保存后,如果我看到图像,图像背景为黑色。我如何获得原始背景?请帮帮我。

我的主要活动是

  import java.io.File;
  import java.io.FileOutputStream;
  import java.util.Random;
  import android.app.Activity;
  import android.graphics.Bitmap;
  import android.graphics.Bitmap.CompressFormat;
  import android.os.Bundle;
  import android.os.Environment;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.Button;
  import android.widget.ImageView;
  import android.widget.RelativeLayout;
  import android.widget.Toast;


   public class Save extends Activity{
     Button save;
    ImageView iv;
     RelativeLayout relative;
    Bitmap bitmap;

     public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.save);
save=(Button)findViewById(R.id.button1);
iv=(ImageView)findViewById(R.id.imageView1);
relative=(RelativeLayout)findViewById(R.id.relative);
save.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        relative.setDrawingCacheEnabled(true);
        relative.buildDrawingCache();
         bitmap = relative.getDrawingCache();

        try {
            File rootFile=new File(Environment.getExternalStorageDirectory().toString()+"/MYPICS");
            rootFile.mkdirs();
            Random generator = new Random();
            int n = 10000;
            n = generator.nextInt(n);
            String fname = "Image-"+ n +".png";

          File  resultingfile=new File(rootFile, fname);

            if (resultingfile.exists ()) resultingfile.delete (); 
            try {
                   FileOutputStream Fout = new FileOutputStream(resultingfile);
                   bitmap.compress(CompressFormat.PNG, 100, Fout);
                   Fout.flush();
                   Fout.close();

            } catch (Exception e) {
                   e.printStackTrace();
            }
      } catch (Exception e) {
    }
  Toast.makeText(getApplicationContext(), "Image is saved", Toast.LENGTH_SHORT).show();

     }
      });

     }
      }

我的xml是

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/relative"
 >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:text="Save" />

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:src="@drawable/ic_launcher" />

   </RelativeLayout>

0 个答案:

没有答案