Bitmap转String进行数据库MySQL保存
前言
解析音乐ID3信息时,需要在扫描时把专辑图解析出来,然后保存到数据中。
PS:20211113日更新指定转换的bitmap指定高宽。
好记性不如烂笔头
正文
这里分为String转Bitmap和bitmap转String来说。
string to bitmap
/**
* string to bitmap
*
* @param string
* @return
*/
public static Bitmap stringToBitmap(String string) {
try {
if (!TextUtils.isEmpty(string)) {
byte[] buffer = Base64.decode(string, Base64.DEFAULT);
if (null != buffer && buffer.length > 0) {
return BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Bitmap转String
这里分为两种,
一种是Bitmap转String
/**
* bitmap to string (Bitmap)
*
* @param bitmap
* @return
*/
public static String bitmapToString(Bitmap bitmap) {
try {
if (bitmap != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
另外一种时Bitmap的buffer转String。
/**
* bitmap to string (buffer)
*
* @param buffer
* @return
*/
public static String bitmapToString(byte[] buffer) {
try {
if (buffer != null && buffer.length > 0) {
return Base64.encodeToString(buffer, Base64.DEFAULT);
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
转换Bitmap时指定高宽
下面的是String转成bytes数组。
当然上面存储时也可以先转成指定高宽再存储。看自己需求。
/**
* string to bitmap
*
* @param string
* @return
*/
public static Bitmap stringToBitmap(String string) {
try {
if (!TextUtils.isEmpty(string)) {
byte[] bytes = Base64.decode(string, Base64.DEFAULT);
if (null != bytes && bytes.length > 0) {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
if (bitmap != null) {
int bmpW = bitmap.getWidth();
int bmpH = bitmap.getHeight();
if (bmpW > 0 && bmpH > 0) {
Matrix m = new Matrix();
m.postScale((float) 420 / bmpW, (float) 420 / bmpH);
return Bitmap.createBitmap(bitmap, 0, 0, bmpW, bmpH, m, true);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
参考文章
相关文章
暂无评论...