如何从ViewPager保存图像?

时间:2013-08-19 09:25:18

标签: java android

我有一个ViewPager活动。我用它来刷图像。我还有一个保存按钮,我需要将当前图像保存到SD卡。但是我收到了一个错误。这是我的XML文件:

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

<android.support.v4.view.ViewPager
  android:id="@+id/view_pager"
  android:layout_width="match_parent"
  android:layout_height="match_parent" />

  <Button
    android:id="@+id/bSave"
    android:layout_width="80dp"
    android:layout_height="40dp"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="15dp"
    android:layout_marginTop="15dp"
    android:text="Save"
    android:layout_alignParentLeft="true"
    android:textSize="24sp"
    android:padding="0dp"
    android:background="@drawable/buttons" />

  </RelativeLayout>

这是我的班级:

public class Photo_gallery extends Activity implements OnClickListener{

    Button save;

    final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Images/");
    boolean success = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.photo_gallery);

        save = (Button) findViewById(R.id.bSave);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
        ImagePagerAdapter adapter = new ImagePagerAdapter();
        viewPager.setAdapter(adapter);

        save.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                final Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                final String fname = "StyleMe-" + n + ".png";

                myDir.mkdirs();

                File image = new File(myDir, fname);

                BitmapDrawable drawable = (BitmapDrawable) viewPager.getBackground();
                Bitmap bitmap = drawable.getBitmap();

                // Encode the file as a PNG image.
                FileOutputStream outStream;
                try {

                    outStream = new FileOutputStream(image);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
                    /* 100 to keep full quality of the image */

                    outStream.flush();
                    outStream.close();
                    success = true;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (success) {
                    Toast.makeText(getApplicationContext(), "Image saved with success at /sdcard/Pictures/SexyImages",
                            Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Error during image saving", Toast.LENGTH_LONG).show();
                }
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse
                        ("file://"
                                                + Environment.getExternalStorageDirectory())));

            }
        });

    }

    private class ImagePagerAdapter extends PagerAdapter {
        private int[] mImages = new int[] {
            R.drawable.p1,
            R.drawable.p2,
            R.drawable.p3,
          .
          .
          .
          .
            R.drawable.p108
        };

        @Override
        public int getCount() {
          return mImages.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
          return view == ((ImageView) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
          Context context = Photo_gallery.this;
          ImageView imageView = new ImageView(context);
          int padding = context.getResources().getDimensionPixelSize(
              R.dimen.padding_medium);
          imageView.setPadding(padding, padding, padding, padding);
          imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
          imageView.setImageResource(mImages[position]);
          ((ViewPager) container).addView(imageView, 0);
          return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
          ((ViewPager) container).removeView((ImageView) object);
        }
      }

    public void onClick(View arg0) {
        // TODO Auto-generated method stub

    }

}

我在这一行得到错误(java.lang.NullPointerException):

Bitmap bitmap = drawable.getBitmap();

1 个答案:

答案 0 :(得分:1)

为什么你不这样做:  按钮保存Clicklistener:

 int currentItem =viewPager.getCurrentItem();
  Drawable drawable = getResource.getDrawable(mImages[currentItem]);
  Bitmap bm =((BitmapDrawable) drawable).getBitmap();