UriImage.java revision 150c4179995cc0a75f934ef194372f9295957ca2
1/*
2 * Copyright (C) 2008 Esmertec AG.
3 * Copyright (C) 2008 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.mms.ui;
19
20import com.android.mms.model.ImageModel;
21import com.android.mms.LogTag;
22import com.google.android.mms.pdu.PduPart;
23import android.database.sqlite.SqliteWrapper;
24
25import android.content.Context;
26import android.database.Cursor;
27import android.graphics.Bitmap;
28import android.graphics.BitmapFactory;
29import android.graphics.Bitmap.CompressFormat;
30import android.net.Uri;
31import android.provider.MediaStore.Images;
32import android.provider.Telephony.Mms.Part;
33import android.text.TextUtils;
34import android.util.Log;
35import android.webkit.MimeTypeMap;
36
37import java.io.ByteArrayOutputStream;
38import java.io.FileNotFoundException;
39import java.io.IOException;
40import java.io.InputStream;
41
42public class UriImage {
43    private static final String TAG = "Mms/image";
44    private static final boolean DEBUG = true;
45    private static final boolean LOCAL_LOGV = false;
46
47    private final Context mContext;
48    private final Uri mUri;
49    private String mContentType;
50    private String mPath;
51    private String mSrc;
52    private int mWidth;
53    private int mHeight;
54
55    public UriImage(Context context, Uri uri) {
56        if ((null == context) || (null == uri)) {
57            throw new IllegalArgumentException();
58        }
59
60        String scheme = uri.getScheme();
61        if (scheme.equals("content")) {
62            initFromContentUri(context, uri);
63        } else if (uri.getScheme().equals("file")) {
64            initFromFile(context, uri);
65        }
66
67        mSrc = mPath.substring(mPath.lastIndexOf('/') + 1);
68
69        if(mSrc.startsWith(".") && mSrc.length() > 1) {
70            mSrc = mSrc.substring(1);
71        }
72
73        // Some MMSCs appear to have problems with filenames
74        // containing a space.  So just replace them with
75        // underscores in the name, which is typically not
76        // visible to the user anyway.
77        mSrc = mSrc.replace(' ', '_');
78
79        mContext = context;
80        mUri = uri;
81
82        decodeBoundsInfo();
83    }
84
85    private void initFromFile(Context context, Uri uri) {
86        mPath = uri.getPath();
87        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
88        String extension = MimeTypeMap.getFileExtensionFromUrl(mPath);
89        if (TextUtils.isEmpty(extension)) {
90            // getMimeTypeFromExtension() doesn't handle spaces in filenames nor can it handle
91            // urlEncoded strings. Let's try one last time at finding the extension.
92            int dotPos = mPath.lastIndexOf('.');
93            if (0 <= dotPos) {
94                extension = mPath.substring(dotPos + 1);
95            }
96        }
97        mContentType = mimeTypeMap.getMimeTypeFromExtension(extension);
98        // It's ok if mContentType is null. Eventually we'll show a toast telling the
99        // user the picture couldn't be attached.
100    }
101
102    private void initFromContentUri(Context context, Uri uri) {
103        Cursor c = SqliteWrapper.query(context, context.getContentResolver(),
104                            uri, null, null, null, null);
105
106        if (c == null) {
107            throw new IllegalArgumentException(
108                    "Query on " + uri + " returns null result.");
109        }
110
111        try {
112            if ((c.getCount() != 1) || !c.moveToFirst()) {
113                throw new IllegalArgumentException(
114                        "Query on " + uri + " returns 0 or multiple rows.");
115            }
116
117            String filePath;
118            if (ImageModel.isMmsUri(uri)) {
119                filePath = c.getString(c.getColumnIndexOrThrow(Part.FILENAME));
120                if (TextUtils.isEmpty(filePath)) {
121                    filePath = c.getString(
122                            c.getColumnIndexOrThrow(Part._DATA));
123                }
124                mContentType = c.getString(
125                        c.getColumnIndexOrThrow(Part.CONTENT_TYPE));
126            } else {
127                filePath = c.getString(
128                        c.getColumnIndexOrThrow(Images.Media.DATA));
129                mContentType = c.getString(
130                        c.getColumnIndexOrThrow(Images.Media.MIME_TYPE));
131            }
132            mPath = filePath;
133        } finally {
134            c.close();
135        }
136    }
137
138    private void decodeBoundsInfo() {
139        InputStream input = null;
140        try {
141            input = mContext.getContentResolver().openInputStream(mUri);
142            BitmapFactory.Options opt = new BitmapFactory.Options();
143            opt.inJustDecodeBounds = true;
144            BitmapFactory.decodeStream(input, null, opt);
145            mWidth = opt.outWidth;
146            mHeight = opt.outHeight;
147        } catch (FileNotFoundException e) {
148            // Ignore
149            Log.e(TAG, "IOException caught while opening stream", e);
150        } finally {
151            if (null != input) {
152                try {
153                    input.close();
154                } catch (IOException e) {
155                    // Ignore
156                    Log.e(TAG, "IOException caught while closing stream", e);
157                }
158            }
159        }
160    }
161
162    public String getContentType() {
163        return mContentType;
164    }
165
166    public String getSrc() {
167        return mSrc;
168    }
169
170    public int getWidth() {
171        return mWidth;
172    }
173
174    public int getHeight() {
175        return mHeight;
176    }
177
178    public PduPart getResizedImageAsPart(int widthLimit, int heightLimit, int byteLimit) {
179        PduPart part = new PduPart();
180
181        byte[] data = getResizedImageData(widthLimit, heightLimit, byteLimit);
182        if (data == null) {
183            if (LOCAL_LOGV) {
184                Log.v(TAG, "Resize image failed.");
185            }
186            return null;
187        }
188
189        part.setData(data);
190        part.setContentType(getContentType().getBytes());
191
192        return part;
193    }
194
195    private static final int NUMBER_OF_RESIZE_ATTEMPTS = 4;
196
197    private byte[] getResizedImageData(int widthLimit, int heightLimit, int byteLimit) {
198        int outWidth = mWidth;
199        int outHeight = mHeight;
200
201        int scaleFactor = 1;
202        while ((outWidth / scaleFactor > widthLimit) || (outHeight / scaleFactor > heightLimit)) {
203            scaleFactor *= 2;
204        }
205
206        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
207            Log.v(TAG, "getResizedImageData: wlimit=" + widthLimit +
208                    ", hlimit=" + heightLimit + ", sizeLimit=" + byteLimit +
209                    ", mWidth=" + mWidth + ", mHeight=" + mHeight +
210                    ", initialScaleFactor=" + scaleFactor);
211        }
212
213        InputStream input = null;
214        try {
215            ByteArrayOutputStream os = null;
216            int attempts = 1;
217
218            do {
219                BitmapFactory.Options options = new BitmapFactory.Options();
220                options.inSampleSize = scaleFactor;
221                input = mContext.getContentResolver().openInputStream(mUri);
222                int quality = MessageUtils.IMAGE_COMPRESSION_QUALITY;
223                try {
224                    Bitmap b = BitmapFactory.decodeStream(input, null, options);
225                    if (b == null) {
226                        return null;
227                    }
228                    if (options.outWidth > widthLimit || options.outHeight > heightLimit) {
229                        // The decoder does not support the inSampleSize option.
230                        // Scale the bitmap using Bitmap library.
231                        int scaledWidth = outWidth / scaleFactor;
232                        int scaledHeight = outHeight / scaleFactor;
233
234                        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
235                            Log.v(TAG, "getResizedImageData: retry scaling using " +
236                                    "Bitmap.createScaledBitmap: w=" + scaledWidth +
237                                    ", h=" + scaledHeight);
238                        }
239
240                        b = Bitmap.createScaledBitmap(b, outWidth / scaleFactor,
241                                outHeight / scaleFactor, false);
242                        if (b == null) {
243                            return null;
244                        }
245                    }
246
247                    // Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY.
248                    // In case that the image byte size is still too large reduce the quality in
249                    // proportion to the desired byte size. Should the quality fall below
250                    // MINIMUM_IMAGE_COMPRESSION_QUALITY skip a compression attempt and we will enter
251                    // the next round with a smaller image to start with.
252                    os = new ByteArrayOutputStream();
253                    b.compress(CompressFormat.JPEG, quality, os);
254                    int jpgFileSize = os.size();
255                    if (jpgFileSize > byteLimit) {
256                        int reducedQuality = quality * byteLimit / jpgFileSize;
257                        if (reducedQuality >= MessageUtils.MINIMUM_IMAGE_COMPRESSION_QUALITY) {
258                            quality = reducedQuality;
259
260                            if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
261                                Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality);
262                            }
263
264                            os = new ByteArrayOutputStream();
265                            b.compress(CompressFormat.JPEG, quality, os);
266                        }
267                    }
268                    b.recycle();        // done with the bitmap, release the memory
269                } catch (java.lang.OutOfMemoryError e) {
270                    Log.w(TAG, "getResizedImageData - image too big (OutOfMemoryError), will try "
271                            + " with smaller scale factor, cur scale factor: " + scaleFactor);
272                    // fall through and keep trying with a smaller scale factor.
273                }
274                if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
275                    Log.v(TAG, "attempt=" + attempts
276                            + " size=" + (os == null ? 0 : os.size())
277                            + " width=" + outWidth / scaleFactor
278                            + " height=" + outHeight / scaleFactor
279                            + " scaleFactor=" + scaleFactor
280                            + " quality=" + quality);
281                }
282                scaleFactor *= 2;
283                attempts++;
284            } while ((os == null || os.size() > byteLimit) && attempts < NUMBER_OF_RESIZE_ATTEMPTS);
285
286            return os == null ? null : os.toByteArray();
287        } catch (FileNotFoundException e) {
288            Log.e(TAG, e.getMessage(), e);
289            return null;
290        } catch (java.lang.OutOfMemoryError e) {
291            Log.e(TAG, e.getMessage(), e);
292            return null;
293        } finally {
294            if (input != null) {
295                try {
296                    input.close();
297                } catch (IOException e) {
298                    Log.e(TAG, e.getMessage(), e);
299                }
300            }
301        }
302    }
303}
304