1package com.bumptech.glide.load.resource.file; 2 3import com.bumptech.glide.load.ResourceDecoder; 4import com.bumptech.glide.load.engine.Resource; 5 6import java.io.File; 7import java.io.FileInputStream; 8import java.io.FileNotFoundException; 9import java.io.IOException; 10import java.io.InputStream; 11 12/** 13 * A decoder that wraps an {@link InputStream} decoder to allow it to decode from a file. 14 * 15 * @param <T> The type of resource that the wrapped InputStream decoder decodes. 16 */ 17public class FileToStreamDecoder<T> implements ResourceDecoder<File, T> { 18 private static final FileOpener DEFAULT_FILE_OPENER = new FileOpener(); 19 20 private ResourceDecoder<InputStream, T> streamDecoder; 21 private final FileOpener fileOpener; 22 23 public FileToStreamDecoder(ResourceDecoder<InputStream, T> streamDecoder) { 24 this(streamDecoder, DEFAULT_FILE_OPENER); 25 } 26 27 // Exposed for testing. 28 FileToStreamDecoder(ResourceDecoder<InputStream, T> streamDecoder, FileOpener fileOpener) { 29 this.streamDecoder = streamDecoder; 30 this.fileOpener = fileOpener; 31 } 32 33 @Override 34 public Resource<T> decode(File source, int width, int height) throws IOException { 35 InputStream is = null; 36 Resource<T> result = null; 37 try { 38 is = fileOpener.open(source); 39 result = streamDecoder.decode(is, width, height); 40 } finally { 41 if (is != null) { 42 try { 43 is.close(); 44 } catch (IOException e) { 45 // Do nothing. 46 } 47 } 48 } 49 return result; 50 } 51 52 @Override 53 public String getId() { 54 return ""; 55 } 56 57 // Visible for testing. 58 static class FileOpener { 59 public InputStream open(File file) throws FileNotFoundException { 60 return new FileInputStream(file); 61 } 62 } 63} 64