我上一篇文章写了《Android加载html中的svg格式图片进行显示〉,有兴趣的同学可以去看看地址:Android加载html中svg格式图片进行显示
但是我们一般在浏览图片时,还会有保存图片到相册或图库的操作,而Android手机自带的相册或图库是不支持查看svg格式的图片的,所以我们需要把svg格式的图片转为jpg或png格式再进行保存,我的例子是保存为jpg格式,png也是一样的,我这里写了个工具类,可以保存jpg,png格式的图片,也可以把svg图片转为jpg进行保存.接下来我贴下我的代码:
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(); } }
用到的第三方开源库:https://github.com/japgolly/svg-android
效果图:
欢迎大家进行交流,指正!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。