public class FileUtils {
public static void savePhoto(final Context context, final String url, final SaveResultCallback saveResultCallback) {
new Thread(new Runnable() {
@Override
public void run() {
File appDir = new File(Environment.getExternalStorageDirectory(), "out_photo");
if (!appDir.exists()) {
appDir.mkdir();
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置以当前时间格式为图片名称
String fileName = df.format(new Date()) + ".jpg";
File file = new File(appDir, fileName);
if (url.endsWith(".svg")) {
//拿到图片在assets目录下的相对路径
String replaceUrl = url.replace("file:///android_asset/", "");
try {
SVG svg = new SVGBuilder().readFromAsset(context.getAssets(), replaceUrl).build();
//拿到svg图片的drawable
PictureDrawable drawable = svg.getDrawable();
//图片背景的画笔
Paint paint = new Paint();
paint.setColor(Color.WHITE);
//图片线条的画笔
Paint paint1 = new Paint();
paint1.setColor(Color.BLACK);
//创建bitmap对象
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawRect(0, 0, bitmap.getWidth() + 50, bitmap.getHeight() + 50, paint);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
FileOutputStream fos = new FileOutputStream(file);
//转为jpg格式并写入到sd卡
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
saveResultCallback.onSavedSuccess();
} catch (IOException e) {
e.printStackTrace();
saveResultCallback.onSavedFailed();
}
} else {
try {
//保存jpg格式的图片到相册中
FileOutputStream fos = new FileOutputStream(file);
InputStream fis = context.getAssets().open(url.replace("file:///android_asset/", ""));
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
fos.flush();
fis.close();
fos.close();
saveResultCallback.onSavedSuccess();
} catch (FileNotFoundException e) {
saveResultCallback.onSavedFailed();
e.printStackTrace();
} catch (IOException e) {
saveResultCallback.onSavedFailed();
e.printStackTrace();
}
}
//保存图片后发送广播通知更新数据库
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
}
}).start();
}
public interface SaveResultCallback {
void onSavedSuccess();
void onSavedFailed();
}
}