android 图片、文件资源资源相关操作
第一步:将图片转化字节数组.
1.得到Bitmap对象
BitmapbitMap = BitmapFactory.decodeResource(getResources(),
R.drawable.main_green);
2.Bitmap ->byte[]
byte[] picByte = getPicByte(bitMap,Bitmap.CompressFormat.PNG, 0);
private byte[] getPicByte(Bitmap src, Bitmap.CompressFormatformat, int quality) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
src.compress(format, quality, os);
byte[] array = os.toByteArray();
return array;
}
第二步:字节数组写文件
public voidWriteFile(String url, String name, byte[] data) {
FileOutputStream fOut = null;
File file =createFile(url, name);
try {
fOut = new FileOutputStream(file);
fOut.write(data);
fOut.flush();
} catch(Exception e) {
e.printStackTrace();
} finally{
try {
if (fOut != null) {
fOut.close();
}
} catch(IOException e) {
Log.e("tag", e.getMessage());
}
}
}
//private final Runtime r =Runtime.getRuntime();
public File createFile(Stringpath, String name) {
File temp, file = null;
try {
temp = newFile(path);
if(!temp.exists()) {
temp.mkdirs();
}
// r.exec("chmod777 " + path);
if (name ==null)
returnnull;
file = newFile(temp, name);
if(!file.exists()) {
try{
file.createNewFile();
}catch (IOException e) {
Log.e("tag",e.getMessage());
}
}
// r.exec("chmod777 " + (path + name));
} catch (Exception e) {
Log.e("tag",e.getMessage());
}
return file;
}
获取本地资源其它方式 以txt文本资源为例
private byte[] getTxtByte() {
byte[] buffer = null;
try {
//gbk.txt文件存放在assets文件夹下
InputStreamis = getAssets().open("gbk.txt");
int size =is.available();
buffer = newbyte[size];
is.read(buffer);
is.close();
} catch (IOException e){
throw newRuntimeException(e);
}
return buffer;
}
从sdcard获取资源显示.
public void setPicture() {
File file = newFile("/sdcard/picture/picurllsit/test.png");
byte[] picByte =getBytesFromFile(file);
imageView.setImageBitmap(Bytes2Bimap(picByte));
}
1.byte[] ->Bitmap
private Bitmap Bytes2Bimap(byte[] b) {
if (b.length != 0) {
returnBitmapFactory.decodeByteArray(b, 0, b.length);
} else{
returnnull;
}
}
2.file-> byte[]
private byte[] getBytesFromFile(File file){
InputStream is = null;
byte[] bytes = null;
try {
is = newFileInputStream(file);
long length =file.length();
if (length> Integer.MAX_VALUE) {
Log.v("TAG","File is too large.....");
}
bytes = newbyte[(int) length];
int offset =0;
int numRead =0;
while (offset< bytes.length
&&(numRead = is.read(bytes, offset,
bytes.length - offset)) >= 0) {
offset+= numRead;
}
if (offset< bytes.length)
thrownew IOException("Cound not completely read
file "
+file.getName());
is.close();
} catch (Exception e){
Log.e("tag",e.getMessage());
} finally {
try {
if(is != null) {
is.close();
}
} catch(Exception ex) {
Log.e("tag",ex.getMessage());
}
}
return bytes;
}