您好,登錄后才能下訂單哦!
這篇文章給大家介紹Android應(yīng)用中怎么將svg圖片轉(zhuǎn)換為jpg格式,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
Android手機自帶的相冊或圖庫是不支持查看svg格式的圖片的,所以我們需要把svg格式的圖片轉(zhuǎn)為jpg或png格式再進行保存,我的例子是保存為jpg格式,png也是一樣的,我這里寫了個工具類,可以保存jpg,png格式的圖片,也可以把svg圖片轉(zhuǎn)為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");//設(shè)置以當前時間格式為圖片名稱 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); //創(chuàng)建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); //轉(zhuǎn)為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(); } } //保存圖片后發(fā)送廣播通知更新數(shù)據(jù)庫 Uri uri = Uri.fromFile(file); context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)); } }).start(); } public interface SaveResultCallback{ void onSavedSuccess(); void onSavedFailed(); } }
關(guān)于Android應(yīng)用中怎么將svg圖片轉(zhuǎn)換為jpg格式就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。