保存图片 首先创建ByteArrayStream对象,然后用BitmapFactroy把图片加载进来,然后compress压缩图片到流, 然后toByteArray()就行了
public void disposeImage()
{
ByteArrayOutputStream outputStream = null;
try
{
SharedPreferences preferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Activity.MODE_PRIVATE);
Editor editor = preferences.edit();
outputStream = new ByteArrayOutputStream();
/*
* 读取和压缩图片资源 并将其保存在 ByteArrayOutputStream对象中
*/
BitmapFactory.decodeResource(getResources(), R.drawable.jt6).compress(CompressFormat.JPEG, 50, outputStream);
String imgBase64 = new String(Base64.encode(outputStream.toByteArray(), Base64.DEFAULT));
editor.putString("image", imgBase64);
editor.commit();
readImage();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (null != outputStream)
{
try
{
outputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public void readImage()
{
ByteArrayInputStream inputStream = null;
try
{
SharedPreferences preferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Activity.MODE_PRIVATE);
String imgbase64 = preferences.getString("image", "");
byte[] imgbyte = Base64.decode(imgbase64.getBytes(), Base64.DEFAULT);
inputStream = new ByteArrayInputStream(imgbyte);
ImageView view = (ImageView) findViewById(R.id.preference_image);
view.setImageDrawable(Drawable.createFromStream(inputStream, "image"));
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (null != inputStream)
{
try
{
inputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}