2011年10月1日星期六

儲存圖像到 SD Card 中

儲存圖像到 SD Card 中

package com.AndroidSaveOnSD;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class AndroidSaveOnSD extends Activity {

ImageView Image;
Button SaveButton;
Bitmap bmImage;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Image = (ImageView)findViewById(R.id.image);
SaveButton = (Button)findViewById(R.id.save);

bmImage = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
Image.setImageBitmap(bmImage);

SaveButton.setOnClickListener(new Button.OnClickListener(){

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

String extStorage = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorage, "myFile.PNG");

try {
OutputStream outStream = new FileOutputStream(file);
bmImage.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(AndroidSaveOnSD.this,
extStorage+"/myFile.PNG",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(AndroidSaveOnSD.this,
e.toString(),
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(AndroidSaveOnSD.this,
e.toString(),
Toast.LENGTH_LONG).show();
}

}});
}
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save Image (myFile.PNG)"
/>
</LinearLayout>


注意須修改 AndroidManifest.xml 添加 "android.permission.WRITE_EXTERNAL_STORAGE" 權限.

相關文章:
- 從 SD Card 中讀取圖像檔案





沒有留言:

發佈留言