ImageView讀取SDCard圖片(Image From SD Card)

1.讀取SDCard內的相片圖片只需要在程式裡(.java)撰寫即可。
public class MainActivity extends Activity
{
private ImageView img;
private Button btn;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//顯示SDCard圖片的ImageView與進行讀取SDCard圖片的Button
img = (ImageView) findViewById(R.id.img);
btn = (Button) findViewById(R.id.sd);

btn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
//確認是否有插入SDCard
if(checkSDCard())
{
//帶入SDCard內的圖片路徑(SDCard: DCIM資料夾/100MEDIA資料夾/001圖片)
img.setImageBitmap(getBitmapFromSDCard("DCIM/100MEDIA/001.jpg"));
}
else Toast.makeText(MainActivity.this,
"尚未插入SDCard",
Toast.LENGTH_SHORT).show();
}
});
}

//確認是否有插入SDCard
private static boolean checkSDCard()
{
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
return true;
}
return false;
}

//讀取SDCard圖片,型態為Bitmap
private static Bitmap getBitmapFromSDCard(String file)
{
try
{
String sd = Environment.getExternalStorageDirectory().toString();
Bitmap bitmap = BitmapFactory.decodeFile(sd + "/" + file);
return bitmap;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}

source: http://dean-android.blogspot.hk/2013/07/androidimageviewsdcardimage-from-sd-card.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s