Glide第二个过程

DataType -> ResourceType

Posted by candy1126xx on May 16, 2017

要缓存

首先获取缓存文件输出流os,把DataType(InputStream、或Bitmap、或GifDrawable)写入os;再获得文件输入流is,从中读出ResourceType。

将InputStream写入os

public boolean encode(InputStream data, OutputStream os) {
    // ByteArrayPool是字节数组池
    byte[] buffer = ByteArrayPool.get().getBytes();
    try {
        int read;
        while ((read = data.read(buffer)) != -1) {
                os.write(buffer, 0, read);
        }
        return true;
    } catch (IOException e) {
        return false;
    } finally {
        ByteArrayPool.get().releaseBytes(buffer);
    }
}

将Bitmap写入os

private Bitmap.CompressFormat getFormat(Bitmap bitmap) {
    if (compressFormat != null) {
        return compressFormat;
    } else if (bitmap.hasAlpha()) {
        return Bitmap.CompressFormat.PNG;
    } else {
        return Bitmap.CompressFormat.JPEG;
    }
}

public boolean encode(Resource<Bitmap> resource, OutputStream os) {
    final Bitmap bitmap = resource.get();
    Bitmap.CompressFormat format = getFormat(bitmap);
    bitmap.compress(format, 100, os);
    return true;
}

将GifDrawable写入os

从is读出Bitmap

Downsampler.decode()。

从is读出GifDrawable

GifResourceDecoder.decode()。

不要缓存

直接从InputStream到Bitmap或GifDrawable,或者从ParcelFileDescriptor到Bitmap。

从ParcelFileDescriptor到Bitmap

public Bitmap decode(ParcelFileDescriptor resource, BitmapPool bitmapPool, int outWidth, int outHeight, DecodeFormat decodeFormat) throws IOException {
    MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
    mediaMetadataRetriever.setDataSource(resource.getFileDescriptor());
    Bitmap result = mediaMetadataRetriever.getFrameAtTime();
    mediaMetadataRetriever.release();
    resource.close();
    return result;
}