import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
public class Demo {
/**
* bitmap 转 byte[]数组
*/
public byte[] bitmap2byteArray(Bitmap bitmap){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
return bytes;
}
/**
* bitmap 转 inputstream
*/
public InputStream bitmap2InputStream(Bitmap bitmap){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
return is;
}
/**
* byte[]数组 转 bitmap
*/
public Bitmap byteArray2Bitmap(byte[] bytes){
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bitmap;
}
/**
* inputstream 转 bitmap
*/
public Bitmap inputStream2Bitmap(InputStream is){
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}
/**
* Drawable 转 bitmap
*/
public Bitmap drawable2Bitmap(Drawable img){
BitmapDrawable bd = (BitmapDrawable) img;
Bitmap bitmap = bd.getBitmap();
return bitmap;
}
/**
* bitmap 转 Drawable
*/
public Drawable bitmap2Drawable(Bitmap bitmap){
BitmapDrawable bd = new BitmapDrawable(bitmap);
Drawable img = bd;
return img;
}
/**
* String 转 byte[]数组
*/
public byte[] string2ByteArray(String str,String charset){
byte[] bytes = null;
if(charset == null){
bytes = str.getBytes();
}else{
try {
//如charset = "utf-8"
bytes = str.getBytes(charset);
} catch (Exception e) {
// TODO: handle exception
}
}
return bytes;
}
/**
* String 转 inputstream
*/
public InputStream string2InputStream(String str){
InputStream is = new ByteArrayInputStream(str.getBytes());
return is;
}
/**
* inputstream 转 String 方法01
*/
public String inputStream2String01(InputStream is) throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
while((i=is.read()) != -1){
baos.write(i);
}
return baos.toString();
}
/**
* inputstream 转 String 方法02
*/
public String inputStream2String02(InputStream is) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while((line=br.readLine()) != null){
sb.append(line+"\n");
}
return sb.toString();
}
/**
* inputstream 转 String 方法03
*/
public String inputSteam2String03(InputStream is) throws IOException{
StringBuilder sb = new StringBuilder();
byte[] b =new byte[1024];
for(int n; (n=is.read(b)) != -1;){
String s = new String(b, 0, n);
sb.append(s);
}
return sb.toString();
}
}