1、这次总结的是将Base64转Bitmap,然后保存到本地相册,我也是翻阅了不少资料后成功搞定,在这里特别感谢一些网上的一些提供资料的大佬。话不多说,开搞!!!
2、首先呢,获取到Base64字符串,我这边的字符串表示为data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD......,前面有data:image/jpeg;base64,这么一串,当然我也不懂Base64啥意思了,只管转换。哈哈,上代码:
/*将Base64转换为Bitmap对象*/
byte[] bytes = Base64.decode(base64Data.split(",")[1], Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
/*将Bitmap对象保存到相册,当然需要读写文件的权限啦,权限自己申请、自行百度,我这里就不多说了,或者可以看我之前的文章(获取金纬度的那一章,有获取权限的简单示例)*/
//保存图片到相册
private void saveScreenShot(Bitmap bitmap) {
String extStorageDirectory = Environment.getExternalStorageDirectory() + File.separator
+ Environment.DIRECTORY_PICTURES + File.separator;
Log.d("baseToPhoto", extStorageDirectory);
OutputStream outStream = null;
String filename;//声明文件名
//以保存时间为文件名
Date date = new Date(System.currentTimeMillis());
@SuppressLint("SimpleDateFormat")
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
filename = sdf.format(date);
File file = new File(extStorageDirectory, filename + ".JPEG");//创建文件,第一个参数为路径,第二个参数为文件名
try {
outStream = new FileOutputStream(file);//创建输入流
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.close();
/** 这三行可以实现相册更新
*Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
*Uri uri = Uri.fromFile(file);intent.setData(uri);
*sendBroadcast(intent);
* //这个广播的目的就是更新图库,发了这个广播进入相册就可以找到你保存的图片了!
*/
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
context.sendBroadcast(intent);
Toast.makeText(context, "保存成功",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(context, "保存失败" + e,
Toast.LENGTH_SHORT).show();
Log.d("baseToPhoto", e.toString());
}
}
ok,就是这么简单。如果你们在做的时候遇到什么问题,欢迎评论,我看到后会第一时间回复。不喜勿喷!!!