将图像从drawables保存到SD卡

时间:2015-03-14 08:02:57

标签: android eclipse bitmap imageview

我需要帮助将图像从drawables保存到SD卡。当我点击保存按钮时,它只从图像视图中将可绘制的a1保存到SD卡。但我想保存当前预览的不可绘制的图像a1。这是我的主要活动。

public class MainActivity extends Activity {

    private static final List<Integer> backgrounds = new ArrayList<Integer>();
    private static final int TOTAL_IMAGES;
    static {
    backgrounds.add(R.drawable.a1);
    backgrounds.add(R.drawable.a2);
    backgrounds.add(R.drawable.a3);
    backgrounds.add(R.drawable.a4);
    backgrounds.add(R.drawable.a5);
    backgrounds.add(R.drawable.a6);
    backgrounds.add(R.drawable.a7);
    backgrounds.add(R.drawable.a8);


        TOTAL_IMAGES = (backgrounds.size() - 1);
    }

    private int currentPosition = 0;
    private ImageView backgroundPreview;
     Bitmap bitmap;
     OutputStream output;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        backgroundPreview = (ImageView) findViewById(R.id.backgroundPreview);
        // Set the default image to be shown to start with
        changePreviewImage(currentPosition);

    }


    public void gotoPreviousImage(View v) {
        int positionToMoveTo = currentPosition;
        positionToMoveTo--;
        if(positionToMoveTo < 0){
            positionToMoveTo = TOTAL_IMAGES;
        }
        changePreviewImage(positionToMoveTo);
    }

    public void save(View v) {
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a1);
        File filepath = Environment.getExternalStorageDirectory();
        File dir = new File(filepath.getAbsolutePath()
        + "/folder/folder/");
        dir.mkdirs();
        File file = new File(dir, "Image1.png");
        Toast.makeText(MainActivity.this, "Image Saved to SD Card",
        Toast.LENGTH_SHORT).show();
        try {
        output = new FileOutputStream(file);
        // Compress into png format image from 0% - 100%
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
        output.flush();
        output.close();
        }
        catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
    }

    public void gotoNextImage(View v) {
        int positionToMoveTo = currentPosition;
        positionToMoveTo++;
        if(currentPosition == TOTAL_IMAGES){
            positionToMoveTo = 0;
        } 

        changePreviewImage(positionToMoveTo);
    }

    public void changePreviewImage(int pos) {
        currentPosition = pos;
        backgroundPreview.setImageResource(backgrounds.get(pos));
        Log.d("Main", "Current position: "+pos);

    }       
};

1 个答案:

答案 0 :(得分:0)

save的第一行:

bitmap = BitmapFactory.decodeResource(getResources(), backgrounds.get(currentPosition)) ;