BitmapFactory.decodeStream siempre devuelve nulos y decodificador skia shows decodifican falsa devuelto

StackOverflow https://stackoverflow.com/questions/3802820

  •  25-09-2019
  •  | 
  •  

Pregunta

imagen de prueba

aquí: http://images.plurk.com/tn_4134189_bf54fe8e270ce41240d534b5133884ee.gif

He intentado varias soluciones encontrarse en internet, pero no hay solución de trabajo.

Estoy usando el siguiente fragmento de código:

Url imageUrl = new Url("http://images.plurk.com/tn_4134189_bf54fe8e270ce41240d534b5133884ee.gif");
Bitmap image = BitmapFactory.decodeStream(imageUrl.openStream());

Siempre conseguir este registro:

DEBUG/skia(1441): --- decoder->decode returned false

Cualquier ayuda? Gracias.

EDIT:

Esas imágenes no pudieron ser decodificado son tampoco se puede demostrar en un WebView. Sin embargo, puede ver si está abierta en un navegador.

¿Fue útil?

Solución

Trate esto como una solución temporal:

Primero se debe agregar la siguiente clase:

  public static class PlurkInputStream extends FilterInputStream {

    protected PlurkInputStream(InputStream in) {
        super(in);
    }

    @Override
    public int read(byte[] buffer, int offset, int count)
        throws IOException {
        int ret = super.read(buffer, offset, count);
        for ( int i = 2; i < buffer.length; i++ ) {
            if ( buffer[i - 2] == 0x2c && buffer[i - 1] == 0x05
                && buffer[i] == 0 ) {
                buffer[i - 1] = 0;
            }
        }
        return ret;
    }

}

A continuación, envolver su flujo original con PlurkInputStream:

Bitmap bitmap = BitmapFactory.decodeStream(new PlurkInputStream(originalInputStream));

Avísame si esto le ayuda.

EDIT:

Lo siento por favor, intente lo siguiente versión en lugar de:

        for ( int i = 6; i < buffer.length - 4; i++ ) {
            if ( buffer[i] == 0x2c ) {
                if ( buffer[i + 2] == 0 && buffer[i + 1] > 0
                    && buffer[i + 1] <= 48 ) {
                    buffer[i + 1] = 0;
                }
                if ( buffer[i + 4] == 0 && buffer[i + 3] > 0
                    && buffer[i + 3] <= 48 ) {
                    buffer[i + 3] = 0;
                }
            }
        }

Tenga en cuenta que esto no es un código eficiente ni es una solución completa / correcta. Se trabajará para la mayoría de los casos, pero no todos.

Otros consejos

I tenía el mismo problema, fue parcialmente fijado por esta clase:

static class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
    super(inputStream);
}

@Override
public long skip(long n) throws IOException {
    long totalBytesSkipped = 0L;
    while (totalBytesSkipped < n) {
        long bytesSkipped = in.skip(n - totalBytesSkipped);
        if (bytesSkipped == 0L) {
              int byte = read();
              if (byte < 0) {
                  break;  // we reached EOF
              } else {
                  bytesSkipped = 1; // we read one byte
              }
       }
        totalBytesSkipped += bytesSkipped;
    }
    return totalBytesSkipped;
}

}

Y:

InputStream in = null;
    try {
        in = new java.net.URL(imageUrl).openStream();
        } catch (MalformedURLException e) {
        e.printStackTrace();
        } catch (IOException e) {
        e.printStackTrace();
        }
Bitmap image = BitmapFactory.decodeStream(new FlushedInputStream(in));

Esto ayudó en la mayoría de los casos, pero esto no es una solución universal. Para más referencia a este informe de error .

Mejor suerte!

He intentado todas las soluciones, pero no resuelto mi problema. Después de algunas pruebas, el problema de la skia decodificador failing pasó mucho cuando la conexión a Internet no es estable. Para mí, lo que obliga a volver a descargar la imagen resuelto el problema.

El problema también se presenta más cuando la imagen es de gran tamaño.

El uso de un bucle se me requiere en la mayoría de los 2 reintentos y la imagen se descargará correctamente.

Bitmap bmp = null;
int retries = 0;
while(bmp == null){
    if (retries == 2){
        break;
    }
    bmp = GetBmpFromURL(String imageURL);
    Log.d(TAG,"Retry...");
    retries++;
}

Esto debería funcionar:

URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
connection.disconnect();
input.close();

myBitmap contiene la imagen.

esto se debe a un error en la clase InputStream en Android. Se puede encontrar una solución alternativa válida y una descripción del error aquí http: // code.google.com/p/android/issues/detail?id=6066

Por razones de memoria, que debe ser implementos Opciones BitmapFactory como esta:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4; // might try 8 also

La función principal de descarga de mapa de bits tal como esto:

Bitmap downloadBitmap(String url) {

    final HttpClient client = AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);

    try {
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            if(DEBUG)Log.w("ImageDownloader", "Error " + statusCode +
                    " while retrieving bitmap from " + url);
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {

                inputStream = entity.getContent();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 4; // might try 8 also
                return BitmapFactory.decodeStream(new FlushedInputStream(inputStream),null,options);

            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (IOException e) {
        getRequest.abort();
        if(DEBUG)Log.w(TAG, "I/O error while retrieving bitmap from " + url, e);
    } catch (IllegalStateException e) {
        getRequest.abort();
        if(DEBUG)Log.w(TAG, "Incorrect URL: " + url);
    } catch (Exception e) {
        getRequest.abort();
        if(DEBUG)Log.w(TAG, "Error while retrieving bitmap from " + url, e);
    } finally {
        if ((client instanceof AndroidHttpClient)) {
            ((AndroidHttpClient) client).close();
        }
    }
    return null;
}

Y tal vez debe ser implementos AsyncTask como este: http://android-developers.blogspot.com/2010/07 /multithreading-for-performance.html

Para mí el problema es con el tipo de color de la imagen: la imagen son de color CYMK = no en RGB

Tal vez este no es su caso, pero podría ser si usted está tratando de decodificar las imágenes CMYK con el espacio de color, en lugar de espacio de color RGB. imágenes CMYK, como éste , no son compatibles con Android, y no se mostrarán incluso en el navegador web de Android. Lea más sobre esta aquí :

No se puede cargar JPEG-imagen con BitmapFactory. decodeFile. Devuelve null

Prueba esto:

HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(entity);
InputStream is = bufferedHttpEntity.getContent();
Drawable d = Drawable.createFromStream(is, "");
//or bitmap
//Bitmap b = BitmapFactory.decodeStream(is);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top