2017-05-06 19 views
0

我在MySQL數據庫中保存圖像的byteArray,然後從Databses中檢索,然後將字符串轉換爲byteArray,然後將byteArray轉換爲Bitmap。但位圖是空的我已經嘗試了很多代碼,但仍爲NULL。 保存圖像在Android(MySQL數據庫)中ImageView的位圖爲空

private String imageviewtobyte(ImageView view){ 
     Bitmap bitmap=((BitmapDrawable) view.getDrawable()).getBitmap(); 
     ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); 
     byteArray = stream.toByteArray(); 
     ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT); 
     return ConvertImage; 

    } 

獲取圖像

imgData=result; 
    byte[] byteArray = Base64.decode(result, Base64.DEFAULT); 
    Bitmap bMap = null; 
    bMap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length); 
    testimg.setImageBitmap(bMap); 

尋找專家,獲取準確的錯誤與解決方案。

+0

您是否檢查過ConvertImage?它是否包含字符串形式的圖像? –

+0

'保存圖像'。該代碼不會上傳圖像並保存在MySQL數據庫中的任何地方。 – greenapps

+0

我在這裏只給出具體的代碼值是正確的和未來的權利。我通過調試檢查,但問題是位圖轉換不工作 –

回答

0
//check result object it is null or not 
if(result != null){ 
    imgData = result; 
    Bitmap bitmap = StringToBitMap(imgData); 
    if(bitmap != null){ 
     testimg.setImageBitmap(bitmap); 
    } 
} 

/** 
* @param encodedString 
* @return bitmap (from given string) 
*/ 
public static Bitmap StringToBitMap(String encodedString){ 
    try{ 
     byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT); 
     Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length); 
     return bitmap; 
    }catch(Exception e){ 
     e.getMessage(); 
     return null; 
    } 
} 
+1

我已經檢查結果是不是空,但讓我檢查通過執行您的方法 –

+0

使用此鏈接來檢查您的字符串是否有效bsae64或不http:// www .askapache.com/online-tools/base64-image-converter/ –

+0

此代碼與OP中的代碼相同。而且,如果位圖爲空,則可以將其分配給圖像視圖。 – greenapps

0

Base64String對於大的位圖無法正常工作。所以首先你必須在將其轉換爲base64String之前減小位圖的大小。我附加了一個用於減小位圖大小的代碼。 您可以在此代碼中使用maxWidth = 960.0和maxheight = 1280.0。

public Bitmap GetBitmap(Bitmap finalimage) { 
    int actualHeight = finalimage.getHeight(); 
    int actualWidth = finalimage.getWidth(); 
    float imgRatio = actualWidth/actualHeight; 
    float maxRatio = maxWidth/maxHeight; 

    if (actualHeight > maxHeight || actualWidth > maxWidth) { 
     if (imgRatio < maxRatio) { 
      imgRatio = maxHeight/actualHeight; 
      actualWidth = (int) (imgRatio * actualWidth); 
      actualHeight = (int) maxHeight; 
     } else if (imgRatio > maxRatio) { 
      imgRatio = maxWidth/actualWidth; 
      actualHeight = (int) (imgRatio * actualHeight); 
      actualWidth = (int) maxWidth; 
     } else { 
      actualHeight = (int) maxHeight; 
      actualWidth = (int) maxWidth; 
     } 
    } 
    finalimage = Bitmap.createScaledBitmap(finalimage, actualWidth, actualHeight, false); 
    return finalimage; 
} 
+0

'Base64String無法很好地處理大位圖。 '。 ???對於位圖?它僅用於字節數組。從來沒有聽說過數組的限制。 – greenapps

+0

這很奇怪,但確實如此。你可以檢查[this](http://stackoverflow.com/questions/28641704/converting-bitmap-to-base64-string-causes-outofmemory-error)鏈接。 –

+0

尺寸不是問題dhruv gangani我檢查了這個 –

相關問題