aboutsummaryrefslogtreecommitdiff
path: root/library/src/main/java/com/bumptech/glide/load/resource/FileToStreamDecoder.java
blob: 907c774695cf1a37d2a66cf0ba7d6d5adaed9fc6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.bumptech.glide.load.resource;

import com.bumptech.glide.load.ResourceDecoder;
import com.bumptech.glide.load.engine.Resource;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * A decoder that wraps an InputStream decoder to allow it to decode from a file.
 * @param <T> The type of resource that the wrapped InputStream decoder decodes.
 */
public class FileToStreamDecoder<T> implements ResourceDecoder<File, T> {
    private static final FileOpener DEFAULT_FILE_OPENER = new DefaultFileOpener();

    private ResourceDecoder<InputStream, T> streamDecoder;
    private final FileOpener fileOpener;

    public FileToStreamDecoder(ResourceDecoder<InputStream, T> streamDecoder) {
        this(streamDecoder, DEFAULT_FILE_OPENER);
    }

    // Exposed for testing.
    FileToStreamDecoder(ResourceDecoder<InputStream, T> streamDecoder, FileOpener fileOpener) {
        this.streamDecoder = streamDecoder;
        this.fileOpener = fileOpener;
    }

    @Override
    public Resource<T> decode(File source, int width, int height) throws IOException {
        InputStream is = null;
        Resource<T> result = null;
        try {
            is = fileOpener.open(source);
            result = streamDecoder.decode(is, width, height);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // Do nothing.
                }
            }

        }
        return result;
    }

    @Override
    public String getId() {
        return "";
    }

    interface FileOpener {
        public InputStream open(File file) throws FileNotFoundException;
    }

    private static class DefaultFileOpener implements FileOpener {

        @Override
        public InputStream open(File file) throws FileNotFoundException {
            return new FileInputStream(file);
        }
    }
}