将assets下的所有图片写到sd卡



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("文件不存在");
  }
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值