package com.example.ninthchapter_two;
import java.io.File;
import java.io.FileOutputStream;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class TestImage extends Activity {
ImageView img = null;
String filepath = "/mnt/sdcard";
Button btn = null;
TextView tv = null;
String filepathimg = "";
Bitmap bmp = null;
int[] drab = new int[] { R.drawable.item1, R.drawable.item2,
R.drawable.item3, R.drawable.item4, R.drawable.item5 };
String[] imgnames = new String[] { "item1", "item2", "item3", "item4",
"item5" };
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.img);
img = (ImageView) findViewById(R.id.im_01);
btn = (Button) findViewById(R.id.btn_show);
tv = (TextView) findViewById(R.id.tv_01);
// 将所有图片存入到SD卡
for (int i = 0; i < drab.length; i++) {
Resources res = getResources();
bmp = BitmapFactory.decodeResource(res, drab[i]);
storeImageToSDCARD(bmp, imgnames[i], filepath);
}
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int nameindex = (int) (Math.random() * imgnames.length);
filepathimg = filepath + "/" + imgnames[nameindex] + ".jpg";
File f = new File(filepathimg);
if (f.exists()) {
Bitmap bm = BitmapFactory.decodeFile(filepathimg);
img.setImageBitmap(bm);
tv.setText(filepathimg);
} else {
tv.setText("文件不存在");
}
}
});
}
// 图片存入到SD卡
public void storeImageToSDCARD(Bitmap colorImage, String ImageName,
String path) {
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
File imagefile = new File(file, ImageName + ".jpg");
if (!imagefile.exists()) {
try {
imagefile.createNewFile();
FileOutputStream fos = new FileOutputStream(imagefile);
colorImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
tv.setText("文件不存在");
}
}
}