summaryrefslogtreecommitdiff
path: root/app/src/main/java/uk/co/blatech/blaupload/ui/NetworkCacheableImageView.java
blob: 043caaef899de33f5ccaf49b716be38efadfc770 (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
/*******************************************************************************
 * Copyright (c) 2013 Chris Banes.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package uk.co.blatech.blaupload.ui;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.opengl.GLES10;
import android.os.AsyncTask;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.RejectedExecutionException;

import javax.microedition.khronos.opengles.GL10;

import uk.co.blatech.blaupload.BlauploadApplication;
import uk.co.blatech.blaupload.R;
import uk.co.blatech.blaupload.data.ImageItem;
import uk.co.senab.bitmapcache.BitmapLruCache;
import uk.co.senab.bitmapcache.CacheableBitmapDrawable;
import uk.co.senab.bitmapcache.CacheableImageView;

/**
 * Simple extension of CacheableImageView which allows downloading of Images of the Internet.
 *
 * This code isn't production quality, but works well enough for this sample.s
 *
 * @author Chris Banes
 */
public class NetworkCacheableImageView extends CacheableImageView {

    public interface OnImageLoadedListener {
        void onImageLoaded(CacheableBitmapDrawable result);
    }

    /**
     * This task simply fetches an Bitmap from the specified URL and wraps it in a wrapper. This
     * implementation is NOT 'best practice' or production ready code.
     */
    private static class ImageUrlAsyncTask
            extends AsyncTask<String, Void, CacheableBitmapDrawable> {

        private final BitmapLruCache mCache;

        private final WeakReference<ImageView> mImageViewRef;
        private final OnImageLoadedListener mListener;

        private final BitmapFactory.Options mDecodeOpts;

        ImageUrlAsyncTask(ImageView imageView, BitmapLruCache cache,
                          BitmapFactory.Options decodeOpts, OnImageLoadedListener listener) {
            mCache = cache;
            mImageViewRef = new WeakReference<ImageView>(imageView);
            mListener = listener;
            mDecodeOpts = decodeOpts;
        }

        @Override
        protected CacheableBitmapDrawable doInBackground(String... params) {

                // Return early if the ImageView has disappeared.
                if (null == mImageViewRef.get()) {
                    return null;
                }

                final String url = params[0];

                // Now we're not on the main thread we can check all caches
                CacheableBitmapDrawable result = mCache.get(url);

                if (null == result) {
                    Log.d("ImageUrlAsyncTask", "Downloading: " + url);

//                    // The bitmap isn't cached so download from the web
//                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
//                    InputStream is = new BufferedInputStream(conn.getInputStream());
                    Bitmap bmp = downloadImage(url);
                    // Add to cache
                    if (bmp != null) {
                        result = mCache.put(url, bmp);
                    }
                } else {
                    Log.d("ImageUrlAsyncTask", "Got from Cache: " + url);
                }

                return result;


        }

        @Override
        protected void onPostExecute(CacheableBitmapDrawable result) {
            super.onPostExecute(result);

            ImageView iv = mImageViewRef.get();
            if (null != iv) {
                iv.setImageDrawable(result);
            }

            if (null != mListener) {
                mListener.onImageLoaded(result);
            }
        }

        private Bitmap downloadImage(String url) {


            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            Bitmap bmp = null;


            int[] maxTextureSize = new int[1];
            maxTextureSize[0] = 4096;
            GLES10.glGetIntegerv(GL10.GL_MAX_TEXTURE_SIZE, maxTextureSize, 0);
            //TODO: Fix out of memory errors
            try {
                HttpResponse response = client.execute(httpGet);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                String[] parts = url.split("\\.");
                String extension = parts[parts.length-1];
                //Create the Bitmap if the file exists
                if (statusCode == 200 && isImageExtension(extension)) {
                    // If the thumbnail wasn't found, show a placeholder
                    HttpEntity entity = response.getEntity();
                    byte[] bytes = EntityUtils.toByteArray(entity);
                    try {
                        bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    } catch (Exception e) {
                        Log.e(NetworkCacheableImageView.class.toString(), "Failed decoding " + url);
                        e.printStackTrace();
                        return bmp;
                    }
                    int bmpHeight = bmp.getHeight();
                    int bmpWidth = bmp.getWidth();
                    if (bmpWidth > maxTextureSize[0]) {

                        float ratio = (float)maxTextureSize[0]/(float)bmpWidth;
                        Matrix matrix = new Matrix();
                        bmpWidth = maxTextureSize[0];
                        bmpHeight = Math.round(bmpHeight * ratio);
                        matrix.postScale(ratio, ratio);
                        bmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeight, matrix, false);
                    } else if (bmpHeight > maxTextureSize[0]) {
                        float ratio = (float)maxTextureSize[0]/(float)bmpHeight;
                        bmpHeight = maxTextureSize[0];
                        bmpWidth = Math.round(bmpWidth * ratio);
                        Matrix matrix = new Matrix();
                        matrix.postScale(ratio, ratio);
                        bmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeight, matrix, false);
                    }
                } else {
                    //If the file doesn't exist, use the placeholder instead
//                    bmp = BitmapFactory.decodeResource(res, R.drawable.x);
                    return bmp;
                }

                //TODO: Error handling (Not sure how we get here)
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return bmp;
        }

        private boolean isImageExtension(String extension) {
            if (extension.equalsIgnoreCase("jpeg") || extension.equalsIgnoreCase("jpg") ||
                    extension.equalsIgnoreCase("gif") || extension.equalsIgnoreCase("png")) {
                return true;
            } else {
                return false;
            }
        }
    }

    private final BitmapLruCache mCache;

    private ImageUrlAsyncTask mCurrentTask;

    public NetworkCacheableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mCache = BlauploadApplication.getApplication(context).getBitmapCache();
    }

    /**
     * Loads the Bitmap.
     *
     * @param url      - URL of image
     * @param fullSize - Whether the image should be kept at the original size
     * @return true if the bitmap was found in the cache
     */
    public boolean loadImage(String url, final boolean fullSize, OnImageLoadedListener listener) {
        // First check whether there's already a task running, if so cancel it
        if (null != mCurrentTask) {
            mCurrentTask.cancel(true);
        }

        // Check to see if the memory cache already has the bitmap. We can
        // safely do
        // this on the main thread.
        BitmapDrawable wrapper = mCache.getFromMemoryCache(url);

        if (null != wrapper) {
            // The cache has it, so just display it
            setImageDrawable(wrapper);
            return true;
        } else {
            // Memory Cache doesn't have the URL, do threaded request...
            setImageDrawable(null);

            BitmapFactory.Options decodeOpts = null;

            if (!fullSize) {
                //decodeOpts = new BitmapFactory.Options();
                //decodeOpts.inSampleSize = 2;
            }

            mCurrentTask = new ImageUrlAsyncTask(this, mCache, decodeOpts, listener);

            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    mCurrentTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
                } else {
                    mCurrentTask.execute(url);
                }
            } catch (RejectedExecutionException e) {
                // This shouldn't happen, but might.
            }

            return false;
        }
    }

}