0
我有大约300-400张图片,尺寸为320x480像素jpg格式。我必须在SD卡上添加这些图像。目前我将这些图像放在我的项目的Drawable文件夹中。现在我想在SD卡上移动这些图像,并且我希望将这些图像用于动画目的。我还想在我的应用程序首次启动时检查是否安装了SD卡。我没有任何想法在Android的SD卡编程,所以请任何人有任何想法或初学者的链接请让我知道。如何在Android的SD CARD上载/添加图像?
CODE
ImageView imgAssets;
String path="";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
path = Environment.getExternalStorageDirectory().toString();
try {
copyFromAsstesToSDCard();
readFromSDCard();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void readFromSDCard() {
// TODO Auto-generated method stub
File dir = Environment.getExternalStorageDirectory();
//File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
//Get the text file
File file = new File(dir.getAbsolutePath()+ "/cat_angry10.jpg");
// i have kept text.txt in the sd-card
//System.out.println(file.toString());
if(file.exists()) // check if file exist
{
try {
Bitmap bitMap = BitmapFactory.decodeFile(Environment.getExternalStorageState() + "/cat_angry10.jpg");
//imgAssets.setImageBitmap(bitMap);
imgAssets.setBackgroundDrawable(new BitmapDrawable(bitMap));
}
catch (Exception e) {
//You'll need to add proper error handling here
e.printStackTrace();
}
}
else
{
System.out.println("Sorry file doesn't exist!!");
}
}
public void copyFromAsstesToSDCard() {
// TODO Auto-generated method stub
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("Images");
} catch (IOException e) {
Log.e("tag", e.getMessage());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("Images/"+filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/" + filename);
System.out.println(out.toString());
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) {
// TODO Auto-generated method stub
byte[] buffer = new byte[1024];
int read;
try {
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
从SD卡读取图像时,我得到的NullPointerException。
感谢 Keyur
感谢您的快速反应.... – Scorpion 2012-01-31 06:37:09
我已经在我的问题添加的代码片段。我得到NullPointerException在我设置位图到ImageView的行。 – Scorpion 2012-02-02 16:25:08