如何在按钮点击时将ViewPager当前图像保存到SD卡

时间:2014-07-31 15:35:03

标签: android android-viewpager android-sdcard android-image android-gallery

我正在使用图像滑动应用程序,我在ViewPager上滑动图像,我想在按钮点击时将当前显示图像保存到SD卡。

我的代码:SwipeActivity.java

package com.td.gridview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

public class SwipeActivity extends Activity {

    protected int curruntPosition;
    protected int hh;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.swipe_view);

        // get intent data
        Intent i = getIntent();

        // Selected image id
        final int position = i.getExtras().getInt("id");

        final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
        ImagePagerAdapter adapter = new ImagePagerAdapter();
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(position);
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub
                // Here you can set the wallpaper
                curruntPosition = arg0;
                if (curruntPosition == arg0) {
                    hh = 1;
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }

        });
        //
        Button bx = (Button) findViewById(R.id.xoom);
        bx.setOnClickListener(new View.OnClickListener() {
            public void onClick(View vx) {
                // // TODO Auto-generated method stub

                if (hh == 1) {
                    // Sending image id to FullScreenActivity
                    Intent i2 = new Intent(getApplicationContext(),
                            Full_Zoom.class);
                    // passing array index
                    i2.putExtra("id", curruntPosition);
                    startActivity(i2);
                } else {
                    // get intent data
                    Intent i3 = getIntent();

                    // Selected image id
                    int position = i3.getExtras().getInt("id");
                    // Sending image id to FullScreenActivity
                    Intent i2 = new Intent(getApplicationContext(),
                            Full_Zoom.class);
                    // passing array index
                    i2.putExtra("id", position);
                    startActivity(i2);
                }

            }
        });
        //

        // Save ViewPager current image  to sd card on button click
        Button b1 = (Button) findViewById(R.id.wll);
        b1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v2) {
                // // TODO Auto-generated method stub

                // Save ViewPager current image  to sd card

            }
        });

    }

    public class ImagePagerAdapter extends PagerAdapter {
        int[] icons = MainActivity.ICONS;

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

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

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

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

}

在上面的代码中找到此代码:这里我想执行从viewpager到SD卡的保存图像

// Save ViewPager current image  to sd card on button click
        Button b1 = (Button) findViewById(R.id.wll);
        b1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v2) {
                // // TODO Auto-generated method stub

                // Save ViewPager current image  to sd card

            }
        });

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

String filename;
Bitmap imageBitmap;

//....
//set file name and bitmap
//....

File imageFile = new File(Environment.getExternalStorageDirectory(), filename);

FileOutputStream out;
try {
    out = new FileOutputStream(imageFile);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); 

    outStream.flush();
    outStream.close();
    success = true;
} catch (Exception e) {
    Log.e(TAG, "Error writing to file: ", e);
} finally {
    if (out != null) {
        try {
            out.close();
        } catch (IOException e) {
                Log.e(TAG, "Error closing file: ", e);
        }
   }

}

答案 1 :(得分:0)

我找到了答案:

package com.td.gridview;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class SwipeActivity extends Activity {

    Context mContext;

    //set save file location example: .getAbsolutePath() + "/Pictures");
    final File myDir = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/");
    boolean success = false;

    protected int curruntPosition;
    protected int hh;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.swipe_view);

        final Context mContext;
        mContext = this;

        // get intent data
        Intent i = getIntent();

        // Selected image id
        final int position = i.getExtras().getInt("id");

        final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
        final ImagePagerAdapter adapter = new ImagePagerAdapter();
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(position);
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub
                // Here you can set the wallpaper
                curruntPosition = arg0;
                if (curruntPosition == arg0) {
                    hh = 1;
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }

        });
        //
        Button bx = (Button) findViewById(R.id.xoom);
        bx.setOnClickListener(new View.OnClickListener() {
            public void onClick(View vx) {
                // // TODO Auto-generated method stub

                if (hh == 1) {
                    // Sending image id to FullScreenActivity
                    Intent i2 = new Intent(getApplicationContext(),
                            Full_Zoom.class);
                    // passing array index
                    i2.putExtra("id", curruntPosition);
                    startActivity(i2);
                } else {
                    // get intent data
                    Intent i3 = getIntent();

                    // Selected image id
                    int position = i3.getExtras().getInt("id");
                    // Sending image id to FullScreenActivity
                    Intent i2 = new Intent(getApplicationContext(),
                            Full_Zoom.class);
                    // passing array index
                    i2.putExtra("id", position);
                    startActivity(i2);
                }

            }
        });
        //

        // Save ViewPager current image to sd card on button click
        Button b1 = (Button) findViewById(R.id.wll);
        b1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v2) {
                // // TODO Auto-generated method stub

                // Save ViewPager current image to sd card

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

                myDir.mkdirs();

                File image = new File(myDir, fname);

                int currentItem = viewPager.getCurrentItem();
                Drawable drawable = mContext.getResources().getDrawable(
                        adapter.mImages[currentItem]);
                Bitmap bitmap = ((BitmapDrawable) 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/temp_image",
                            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://mnt/sdcard/"
                                + Environment.getExternalStorageDirectory())));

            }

            //

        });

    }

    public class ImagePagerAdapter extends PagerAdapter {
        protected int[] mImages = MainActivity.ICONS;
        int[] icons = MainActivity.ICONS;

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

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

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

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

}