在Android(MySQL数据库)中ImageView的位图为空

问题描述:

我在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

我在这里只给出具体的代码值是正确的和未来的权利。我通过调试检查,但问题是位图转换不工作 –

//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

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://*.com/questions/28641704/converting-bitmap-to-base64-string-causes-outofmemory-error)链接。 –

+0

尺寸不是问题dhruv gangani我检查了这个 –