UriImage.java revision e7cee115c2e0deada90627fd265139c22fdc32d4
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 = uri.getPath(); 128 mContentType = c.getString( 129 c.getColumnIndexOrThrow(Images.Media.MIME_TYPE)); 130 } 131 mPath = filePath; 132 } finally { 133 c.close(); 134 } 135 } 136 137 private void decodeBoundsInfo() { 138 InputStream input = null; 139 try { 140 input = mContext.getContentResolver().openInputStream(mUri); 141 BitmapFactory.Options opt = new BitmapFactory.Options(); 142 opt.inJustDecodeBounds = true; 143 BitmapFactory.decodeStream(input, null, opt); 144 mWidth = opt.outWidth; 145 mHeight = opt.outHeight; 146 } catch (FileNotFoundException e) { 147 // Ignore 148 Log.e(TAG, "IOException caught while opening stream", e); 149 } finally { 150 if (null != input) { 151 try { 152 input.close(); 153 } catch (IOException e) { 154 // Ignore 155 Log.e(TAG, "IOException caught while closing stream", e); 156 } 157 } 158 } 159 } 160 161 public String getContentType() { 162 return mContentType; 163 } 164 165 public String getSrc() { 166 return mSrc; 167 } 168 169 public int getWidth() { 170 return mWidth; 171 } 172 173 public int getHeight() { 174 return mHeight; 175 } 176 177 public PduPart getResizedImageAsPart(int widthLimit, int heightLimit, int byteLimit) { 178 PduPart part = new PduPart(); 179 180 byte[] data = getResizedImageData(widthLimit, heightLimit, byteLimit); 181 if (data == null) { 182 if (LOCAL_LOGV) { 183 Log.v(TAG, "Resize image failed."); 184 } 185 return null; 186 } 187 188 part.setData(data); 189 part.setContentType(getContentType().getBytes()); 190 191 return part; 192 } 193 194 private static final int NUMBER_OF_RESIZE_ATTEMPTS = 4; 195 196 private byte[] getResizedImageData(int widthLimit, int heightLimit, int byteLimit) { 197 int outWidth = mWidth; 198 int outHeight = mHeight; 199 200 int scaleFactor = 1; 201 while ((outWidth / scaleFactor > widthLimit) || (outHeight / scaleFactor > heightLimit)) { 202 scaleFactor *= 2; 203 } 204 205 if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { 206 Log.v(TAG, "getResizedImageData: wlimit=" + widthLimit + 207 ", hlimit=" + heightLimit + ", sizeLimit=" + byteLimit + 208 ", mWidth=" + mWidth + ", mHeight=" + mHeight + 209 ", initialScaleFactor=" + scaleFactor); 210 } 211 212 InputStream input = null; 213 try { 214 ByteArrayOutputStream os = null; 215 int attempts = 1; 216 217 do { 218 BitmapFactory.Options options = new BitmapFactory.Options(); 219 options.inSampleSize = scaleFactor; 220 input = mContext.getContentResolver().openInputStream(mUri); 221 int quality = MessageUtils.IMAGE_COMPRESSION_QUALITY; 222 try { 223 Bitmap b = BitmapFactory.decodeStream(input, null, options); 224 if (b == null) { 225 return null; 226 } 227 if (options.outWidth > widthLimit || options.outHeight > heightLimit) { 228 // The decoder does not support the inSampleSize option. 229 // Scale the bitmap using Bitmap library. 230 int scaledWidth = outWidth / scaleFactor; 231 int scaledHeight = outHeight / scaleFactor; 232 233 if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { 234 Log.v(TAG, "getResizedImageData: retry scaling using " + 235 "Bitmap.createScaledBitmap: w=" + scaledWidth + 236 ", h=" + scaledHeight); 237 } 238 239 b = Bitmap.createScaledBitmap(b, outWidth / scaleFactor, 240 outHeight / scaleFactor, false); 241 if (b == null) { 242 return null; 243 } 244 } 245 246 // Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY. 247 // In case that the image byte size is still too large reduce the quality in 248 // proportion to the desired byte size. Should the quality fall below 249 // MINIMUM_IMAGE_COMPRESSION_QUALITY skip a compression attempt and we will enter 250 // the next round with a smaller image to start with. 251 os = new ByteArrayOutputStream(); 252 b.compress(CompressFormat.JPEG, quality, os); 253 int jpgFileSize = os.size(); 254 if (jpgFileSize > byteLimit) { 255 int reducedQuality = quality * byteLimit / jpgFileSize; 256 if (reducedQuality >= MessageUtils.MINIMUM_IMAGE_COMPRESSION_QUALITY) { 257 quality = reducedQuality; 258 259 if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { 260 Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality); 261 } 262 263 os = new ByteArrayOutputStream(); 264 b.compress(CompressFormat.JPEG, quality, os); 265 } 266 } 267 b.recycle(); // done with the bitmap, release the memory 268 } catch (java.lang.OutOfMemoryError e) { 269 Log.w(TAG, "getResizedImageData - image too big (OutOfMemoryError), will try " 270 + " with smaller scale factor, cur scale factor: " + scaleFactor); 271 // fall through and keep trying with a smaller scale factor. 272 } 273 if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { 274 Log.v(TAG, "attempt=" + attempts 275 + " size=" + (os == null ? 0 : os.size()) 276 + " width=" + outWidth / scaleFactor 277 + " height=" + outHeight / scaleFactor 278 + " scaleFactor=" + scaleFactor 279 + " quality=" + quality); 280 } 281 scaleFactor *= 2; 282 attempts++; 283 } while ((os == null || os.size() > byteLimit) && attempts < NUMBER_OF_RESIZE_ATTEMPTS); 284 285 return os == null ? null : os.toByteArray(); 286 } catch (FileNotFoundException e) { 287 Log.e(TAG, e.getMessage(), e); 288 return null; 289 } catch (java.lang.OutOfMemoryError e) { 290 Log.e(TAG, e.getMessage(), e); 291 return null; 292 } finally { 293 if (input != null) { 294 try { 295 input.close(); 296 } catch (IOException e) { 297 Log.e(TAG, e.getMessage(), e); 298 } 299 } 300 } 301 } 302} 303