Android应用中怎么将svg图片转换为jpg格式-创新互联
这篇文章给大家介绍Android应用中怎么将svg图片转换为jpg格式,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
创新互联主要从事做网站、网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务泗县,十载网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18980820575Android手机自带的相册或图库是不支持查看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(); } }
文章题目:Android应用中怎么将svg图片转换为jpg格式-创新互联
文章链接:http://cdiso.cn/article/coopcp.html