2012-04-24 134 views
3

我有一個jpg圖像作爲字節數組。我怎樣才能將這個字節數組轉儲爲JPG格式,然後在其上寫入canavas然後將其保存在SD卡上?在jpg圖像上繪製文本android

歡迎任何想法。謝謝。

+0

檢查我這裏http://stackoverflow.com/questions/6159186/how-do-i-write-text-over-a-picture-in-android-and回答-save-it – MKJParekh 2012-04-24 12:49:22

回答

4

使用BitmapFactory.decodeByteArray()獲得Bitmap,然後使用該位圖上創建一個Canvas,並繪製文本那裏。最後,通過使用Bitmap.compress()保存:

Bitmap bmp = BitmapFactory.decodeByteArray(myArray, 0, myArray.length).copy(Bitmap.Config.RGBA_8888, true); //myArray is the byteArray containing the image. Use copy() to create a mutable bitmap. Feel free to change the config-type. Consider doing this in two steps so you can recycle() the immutable bitmap. 
Canvas canvas = new Canvas(bmp); 
canvas.drawText("Hello Image", xposition, yposition, textpaint); //x/yposition is where the text will be drawn. textpaint is the Paint object to draw with. 

OutputStream os = new FileOutputStream(dstfile); //dstfile is a File-object that you want to save to. You probably need to add some exception-handling here. 
bmp.compress(CompressFormat.JPG, 100, os); //Output as JPG with maximum quality. 
os.flush(); 
os.close();//Don't forget to close the stream. 
+0

不可變的位圖傳遞給Canvas構造函數,我得到這個異常。任何想法我做錯了什麼? – opc0de 2012-04-24 12:59:36

+0

@ opc0de啊,忘記了,'decodeByteArray()'返回一個不可變的(不可修改的)位圖,所以你不能直接在它上面繪製。 我在示例中添加了'.copy()'命令。這會創建一個可變的相同位圖。 – Jave 2012-04-24 13:06:22

+0

非常感謝! – opc0de 2012-04-24 13:13:54

2
  1. 使用BitmapFactory
    1. 創建Canvas
    2. 上繪製text解碼字節數組
    3. Save你的位圖SD storage

希望這有助於。

+2

我喜歡看到人們如何-1這個答案。我猜這是同一種...... emm ......開發者......誰更喜歡Ctrl-C Ctrl-V答案:) – EvilDuck 2014-06-20 19:50:20