2011-02-27 83 views
11

我使用的是使用畫布將圖像合併爲1的代碼。我向ImageView顯示圖像看起來很好。但是,當我嘗試將其顯示到WebView中時,它顯示的圖像背景爲黑色。我嘗試在HTML中更改背景顏色,但不會更改顏色。或使透明。誰能幫忙? Result is here上面的圖片在ImageView中,下面的圖片在WebView中。爲什麼位圖到Base64在android中顯示webview上的黑色背景?

public class MyBimapTest extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    ImageView img1 = (ImageView) findViewById(R.id.ImageView01); 

    img1.setVisibility(View.INVISIBLE); 
    Drawable dra1 = img1.getDrawable(); 
    Bitmap map1 = ((BitmapDrawable) dra1).getBitmap(); 
    ImageView img2 = (ImageView) findViewById(R.id.ImageView02); 
    img2.setVisibility(View.INVISIBLE); 
    Drawable dra2 = img2.getDrawable(); 
    Bitmap map2 = ((BitmapDrawable) dra2).getBitmap(); 

    // *** 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    map1.compress(Bitmap.CompressFormat.JPEG, 100, baos); 

    byte[] b = baos.toByteArray(); 
    String abc = Base64.encodeBytes(b); 

    byte[] byt = null; 
    try { 
     byt = Base64.decode(abc); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    map1 = BitmapFactory.decodeByteArray(byt, 0, byt.length); 

    // *** 
    Bitmap map = combineImages(map1, map2); 
    ByteArrayOutputStream bbb = new ByteArrayOutputStream(); 
    map.compress(Bitmap.CompressFormat.JPEG, 100, bbb); 

    byte[] bit = bbb.toByteArray(); 

    String imgToString = Base64.encodeBytes(bit); 

    String imgTag = "<img src='data:image/jpg;base64," + imgToString 
      + "' align='left' bgcolor='ff0000'/>"; 

    WebView webView = (WebView) findViewById(R.id.storyView); 
    webView.loadData(imgTag, "text/html", "utf-8"); 
    Drawable end = new BitmapDrawable(map); 

    ImageView img3 = (ImageView) findViewById(R.id.ImageView03); 
    img3.setImageBitmap(map); 
} 

public Bitmap combineImages(Bitmap c, Bitmap s) { 
    Bitmap cs = null; 
    int width, height = 0; 

    width = c.getWidth() + (s.getWidth()/2); 
    height = c.getHeight() + (s.getHeight()/2); 

    cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 

    Canvas comboImage = new Canvas(cs); 

    comboImage.drawBitmap(c, 0f, 0f, null); 
    comboImage.drawBitmap(s, c.getWidth() - (s.getWidth()/2), c 
      .getHeight() 
      - (s.getHeight()/2), null); 
    return cs; 
} 

}

回答

21

JPEG格式不支持Alpha透明度,這就是爲什麼當你轉換你的原始圖像JPEG透明背景變成了黑色。

使用PNG格式來代替:

map1.compress(Bitmap.CompressFormat.PNG, 100, baos); 

String imgTag = "<img src='data:image/png;base64," + imgToString    
    + "' align='left' bgcolor='ff0000'/>"; 
+0

十分感謝您。它完美的作品... – Arslan 2011-02-27 15:10:28

+0

非常感謝...以前使用壓縮格式JPEG。 在此處獲取更多詳細信息 http://developer.android.com/reference/android/graphics/Bitmap.CompressFormat.html – CoDe 2013-10-10 06:47:06

+0

直到compress()的完美答案然而,在哪裏應用imgTag?你能幫我麼? – VVB 2016-11-10 09:31:22

相關問題