aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/thedevstack/conversationsplus/utils/ImageUtil.java
blob: 3c3e1c99c84a1a9796ca3c9fa11e9430b9aae191 (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package de.thedevstack.conversationsplus.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.net.Uri;
import android.util.Log;
import android.util.LruCache;

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

import de.thedevstack.conversationsplus.entities.Message;
import de.thedevstack.conversationsplus.persistance.FileBackend;

/**
 * This util provides
 */
public final class ImageUtil {
    private static LruCache<String, Bitmap> BITMAP_CACHE;

    /**
     * Returns a bitmap from the cache.
     * @see LruCache#get(Object) for details
     * @param key the key of the bitmap to get
     * @return the bitmap
     */
    public static Bitmap getBitmapFromCache(String key) {
        return BITMAP_CACHE.get(key);
    }

    /**
     * Adds a bitmap with the given key to the cache.
     * @see LruCache#put(Object, Object) for details
     * @param key the key to identify this bitmap
     * @param bitmap the bitmap to cache
     */
    public static void addBitmapToCache(String key, Bitmap bitmap) {
        BITMAP_CACHE.put(key, bitmap);
    }

    /**
     * Removes the bitmap with given key from the cache.
     * @param key the key of the bitmap to remove
     */
    public static void removeBitmapFromCache(String key) {
        BITMAP_CACHE.remove(key);
    }

    /**
     * Clears the cache.
     * @see LruCache#evictAll() for more details.
     */
    public static void evictBitmapCache() {
        BITMAP_CACHE.evictAll();
    }

    /**
     * Initializes the bitmap cache.
     * This has to be executed once on application start.
     * @see LruCache#LruCache(int) for details
     */
    public static void initBitmapCache() {
        Log.i("Conversations+ImageUtil", "Initializing BitmapCache");
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;
        BITMAP_CACHE = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(final String key, final Bitmap bitmap) {
                return bitmap.getByteCount() / 1024;
            }
        };
    }

    /**
     * Resizes a given bitmap and return a new and resized bitmap.
     * The bitmap is only resized if either the width or the height of the original bitmap is smaller than the given size.
     * @param originalBitmap the bitmap to resize
     * @param size the size to scale to
     * @return new and resized bitmap or the original bitmap if width and height are smaller than size
     */
    public static Bitmap resize(Bitmap originalBitmap, int size) {
        int w = originalBitmap.getWidth();
        int h = originalBitmap.getHeight();
        if (Math.max(w, h) > size) {
            int scalledW;
            int scalledH;
            if (w <= h) {
                scalledW = (int) (w / ((double) h / size));
                scalledH = size;
            } else {
                scalledW = size;
                scalledH = (int) (h / ((double) w / size));
            }
            return Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
        } else {
            return originalBitmap;
        }
    }

    /**
     * Returns the rotation from the exif information of an image identified with the given uri.
     * The orientation is retrieved by parsing the stream of the image.
     * FileNotFoundException is silently ignored.
     * @param image the uri of the image to get the rotation
     * @return the rotation value for the image, <code>0</code> if the file cannot be found.
     */
    public static int getRotation(Uri image) {
        InputStream is = null;
        try {
            is = StreamUtil.openInputStreamFromContentResolver(image);
            return ExifHelper.getOrientation(is);
        } catch (FileNotFoundException e) {
            return 0;
        } finally {
            StreamUtil.close(is);
        }
    }

    /**
     * Returns a thumbnail for a bitmap in a message.
     * @param message the message to get the thumbnail for
     * @param size the size to resize the original image to
     * @param cacheOnly whether only cached images should be returned or not
     * @return the resized thumbail
     * @throws FileNotFoundException if the original image does not exist anymore or an IOException occurs.
     */
    public static Bitmap getThumbnail(Message message, int size, boolean cacheOnly)
            throws FileNotFoundException {
        Bitmap thumbnail = ImageUtil.getBitmapFromCache(message.getUuid());
        if ((thumbnail == null) && (!cacheOnly)) {
            File file = FileBackend.getFile(message);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = calcSampleSize(file, size);
            Bitmap fullsize = BitmapFactory.decodeFile(file.getAbsolutePath(),options);
            if (fullsize == null) {
                throw new FileNotFoundException();
            }
            thumbnail = resize(fullsize, size);
            thumbnail = rotate(thumbnail, file.getAbsolutePath());

            ImageUtil.addBitmapToCache(message.getUuid(), thumbnail);
        }
        return thumbnail;
    }

    /**
     * Rotates an bitmap. Only the values 90°, 180° and 270° are considered to rotate the image.
     * The orientation information is read using the ExifInterface.
     * @param original the original bitmap
     * @param srcPath the path to the original bitmap (used to read the exif information)
     * @return rotated bitmap, or original bitmap if criteria are not met
     * @throws IOException
     */
    public static Bitmap rotate(Bitmap original, String srcPath) {
        try {
            ExifInterface exif = new ExifInterface(srcPath);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
            int rotation = 0;
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotation = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotation = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotation = 270;
                    break;
            }
            if (rotation > 0) {
                return rotate(original, rotation);
            }
        } catch (IOException e) {
            Log.w("filebackend", "Error while rotating image, returning original (" + e.getMessage() + ")");
        }
        return original;
    }

    /**
     * Rotates a bitmap with given degrees.
     * @param bitmap the bitmap to be rotated
     * @param degree the degrees to rotate the bitmap
     * @return a newly created bitmap
     */
    public static Bitmap rotate(Bitmap bitmap, int degree) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix mtx = new Matrix();
        mtx.postRotate(degree);
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
    }


    public static Bitmap cropCenterSquare(Uri image, int size) {
        if (image == null) {
            return null;
        }
        InputStream is = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = calcSampleSize(image, size);
            is = StreamUtil.openInputStreamFromContentResolver(image);
            Bitmap input = BitmapFactory.decodeStream(is, null, options);
            if (input == null) {
                return null;
            } else {
                int rotation = getRotation(image);
                if (rotation > 0) {
                    input = rotate(input, rotation);
                }
                return cropCenterSquare(input, size);
            }
        } catch (FileNotFoundException e) {
            return null;
        } finally {
            StreamUtil.close(is);
        }
    }

    public static Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
        if (image == null) {
            return null;
        }
        InputStream is = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = calcSampleSize(image,Math.max(newHeight, newWidth));
            is = StreamUtil.openInputStreamFromContentResolver(image);
            Bitmap source = BitmapFactory.decodeStream(is, null, options);
            if (source == null) {
                return null;
            }
            int sourceWidth = source.getWidth();
            int sourceHeight = source.getHeight();
            float xScale = (float) newWidth / sourceWidth;
            float yScale = (float) newHeight / sourceHeight;
            float scale = Math.max(xScale, yScale);
            float scaledWidth = scale * sourceWidth;
            float scaledHeight = scale * sourceHeight;
            float left = (newWidth - scaledWidth) / 2;
            float top = (newHeight - scaledHeight) / 2;

            RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
            Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(dest);
            canvas.drawBitmap(source, null, targetRect, null);
            return dest;
        } catch (FileNotFoundException e) {
            return null;
        } finally {
            StreamUtil.close(is);
        }
    }

    public static Bitmap cropCenterSquare(Bitmap input, int size) {
        int w = input.getWidth();
        int h = input.getHeight();

        float scale = Math.max((float) size / h, (float) size / w);

        float outWidth = scale * w;
        float outHeight = scale * h;
        float left = (size - outWidth) / 2;
        float top = (size - outHeight) / 2;
        RectF target = new RectF(left, top, left + outWidth, top + outHeight);

        Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        canvas.drawBitmap(input, null, target, null);
        return output;
    }

    public static int calcSampleSize(Uri image, int size) throws FileNotFoundException {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(StreamUtil.openInputStreamFromContentResolver(image), null, options);
        return calcSampleSize(options, size);
    }

    public static int calcSampleSize(File image, int size) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(image.getAbsolutePath(), options);
        return calcSampleSize(options, size);
    }

    public static int calcSampleSize(BitmapFactory.Options options, int size) {
        int height = options.outHeight;
        int width = options.outWidth;
        int inSampleSize = 1;

        if (height > size || width > size) {
            int halfHeight = height / 2;
            int halfWidth = width / 2;

            while ((halfHeight / inSampleSize) > size
                    && (halfWidth / inSampleSize) > size) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    private ImageUtil() {
        // Static helper class
    }
}