【问题标题】:How to check if the bitmap has data?如何检查位图是否有数据?
【发布时间】:2019-11-02 03:54:55
【问题描述】:

我有什么:我正在从 URL 下载图像并将其转换为位图。

发生了什么:有时服务器返回一个图像,有时只是一个小的占位符。

我要做什么:如何找出位图是否包含图像(与很小的占位符相比,图像的大小相当适中)。

用于从 URL 获取图像的代码:

private Bitmap getBitmap(String url)
{
    File f=fileCache.getFile(url);

    //from SD cache
    Bitmap b = decodeFile(f);
    if(b!=null)
        return b;

    //from web
    try {
        Bitmap bitmap=null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Exception ex){
        ex.printStackTrace();
        return null;
    }
}

【问题讨论】:

  • 您确实提到占位符小于典型图像。测量位图的宽/高是否足以区分两者?

标签: android android-bitmap


【解决方案1】:

确定图像的最小宽度和高度,如果位图高度和宽度小于这个最小值,则表示这是占位符。例如

Bitmap bitmap = decodeFile(f);
int minHeight = 500;
int minWidth = 500;
if(bitmap.getHeight() < minHeight && bitmap.getWidth() < minWidth){
//it is a placeholder
}

【讨论】:

    【解决方案2】:

    如果占位符每次的大小都相同,那么只需将 60 替换为它的高度(以像素为单位)。如果Bitmap 的高度与您的占位符匹配,则这只需要Bitmap 并返回true

    private bool isPlaceholder (Bitmap bmp)
    {
        //presumably, the placeholder never changes size
        //if it's 60 then we've got a placeholder
        if (bmp.Height == 60){
            return true;
        }
        else{
            return false;
        }
    }
    

    编辑:这仅适用于占位符始终小于图像的情况。否则,您可能需要更复杂的逻辑,例如检查图像的高度 大小(以字节为单位)。或高度和宽度。如果它的高度总是更小,那么你可以使用上面的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      相关资源
      最近更新 更多