use of android.graphics.BitmapFactory.Options in project react-native-image-picker by marcshilling.
the class ImagePickerModule method getResizedImage.
/**
* Create a resized image to fulfill the maxWidth/maxHeight, quality and rotation values
*
* @param realPath
* @param initialWidth
* @param initialHeight
* @return resized file
*/
private File getResizedImage(final String realPath, final int initialWidth, final int initialHeight) {
Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap photo = BitmapFactory.decodeFile(realPath, options);
if (photo == null) {
return null;
}
Bitmap scaledphoto = null;
if (maxWidth == 0 || maxWidth > initialWidth) {
maxWidth = initialWidth;
}
if (maxHeight == 0 || maxWidth > initialHeight) {
maxHeight = initialHeight;
}
double widthRatio = (double) maxWidth / initialWidth;
double heightRatio = (double) maxHeight / initialHeight;
double ratio = (widthRatio < heightRatio) ? widthRatio : heightRatio;
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
matrix.postScale((float) ratio, (float) ratio);
ExifInterface exif;
try {
exif = new ExifInterface(realPath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
} catch (IOException e) {
e.printStackTrace();
}
scaledphoto = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), matrix, true);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
scaledphoto.compress(Bitmap.CompressFormat.JPEG, quality, bytes);
File f = createNewFile();
FileOutputStream fo;
try {
fo = new FileOutputStream(f);
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// recycle to avoid java.lang.OutOfMemoryError
if (photo != null) {
scaledphoto.recycle();
photo.recycle();
scaledphoto = null;
photo = null;
}
return f;
}
use of android.graphics.BitmapFactory.Options in project react-native-image-picker by marcshilling.
the class ImagePickerModule method onActivityResult.
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
//robustness code
if (callback == null || (cameraCaptureURI == null && requestCode == REQUEST_LAUNCH_IMAGE_CAPTURE) || (requestCode != REQUEST_LAUNCH_IMAGE_CAPTURE && requestCode != REQUEST_LAUNCH_IMAGE_LIBRARY && requestCode != REQUEST_LAUNCH_VIDEO_LIBRARY && requestCode != REQUEST_LAUNCH_VIDEO_CAPTURE)) {
return;
}
responseHelper.cleanResponse();
// user cancel
if (resultCode != Activity.RESULT_OK) {
responseHelper.invokeCancel(callback);
callback = null;
return;
}
Uri uri;
switch(requestCode) {
case REQUEST_LAUNCH_IMAGE_CAPTURE:
uri = cameraCaptureURI;
this.fileScan(uri.getPath());
break;
case REQUEST_LAUNCH_IMAGE_LIBRARY:
uri = data.getData();
break;
case REQUEST_LAUNCH_VIDEO_LIBRARY:
responseHelper.putString("uri", data.getData().toString());
responseHelper.putString("path", getRealPathFromURI(data.getData()));
responseHelper.invokeResponse(callback);
callback = null;
return;
case REQUEST_LAUNCH_VIDEO_CAPTURE:
final String path = getRealPathFromURI(data.getData());
responseHelper.putString("uri", data.getData().toString());
responseHelper.putString("path", path);
this.fileScan(path);
responseHelper.invokeResponse(callback);
callback = null;
return;
default:
uri = null;
}
String realPath = getRealPathFromURI(uri);
boolean isUrl = false;
if (realPath != null) {
try {
URL url = new URL(realPath);
isUrl = true;
} catch (MalformedURLException e) {
// not a url
}
}
// image isn't in memory cache
if (realPath == null || isUrl) {
try {
File file = createFileFromURI(uri);
realPath = file.getAbsolutePath();
uri = Uri.fromFile(file);
} catch (Exception e) {
// image not in cache
responseHelper.putString("error", "Could not read photo");
responseHelper.putString("uri", uri.toString());
responseHelper.invokeResponse(callback);
callback = null;
return;
}
}
int currentRotation = 0;
try {
ExifInterface exif = new ExifInterface(realPath);
// extract lat, long, and timestamp and add to the response
float[] latlng = new float[2];
exif.getLatLong(latlng);
float latitude = latlng[0];
float longitude = latlng[1];
if (latitude != 0f || longitude != 0f) {
responseHelper.putDouble("latitude", latitude);
responseHelper.putDouble("longitude", longitude);
}
final String timestamp = exif.getAttribute(ExifInterface.TAG_DATETIME);
final SimpleDateFormat exifDatetimeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
final DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
final String isoFormatString = new StringBuilder(isoFormat.format(exifDatetimeFormat.parse(timestamp))).append("Z").toString();
responseHelper.putString("timestamp", isoFormatString);
} catch (Exception e) {
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
boolean isVertical = true;
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
isVertical = false;
currentRotation = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
isVertical = false;
currentRotation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
currentRotation = 180;
break;
}
responseHelper.putInt("originalRotation", currentRotation);
responseHelper.putBoolean("isVertical", isVertical);
} catch (IOException e) {
e.printStackTrace();
responseHelper.invokeError(callback, e.getMessage());
callback = null;
return;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(realPath, options);
int initialWidth = options.outWidth;
int initialHeight = options.outHeight;
// don't create a new file if contraint are respected
if (((initialWidth < maxWidth && maxWidth > 0) || maxWidth == 0) && ((initialHeight < maxHeight && maxHeight > 0) || maxHeight == 0) && quality == 100 && (rotation == 0 || currentRotation == rotation)) {
responseHelper.putInt("width", initialWidth);
responseHelper.putInt("height", initialHeight);
} else {
File resized = getResizedImage(realPath, initialWidth, initialHeight);
if (resized == null) {
responseHelper.putString("error", "Can't resize the image");
} else {
realPath = resized.getAbsolutePath();
uri = Uri.fromFile(resized);
BitmapFactory.decodeFile(realPath, options);
responseHelper.putInt("width", options.outWidth);
responseHelper.putInt("height", options.outHeight);
}
}
if (saveToCameraRoll && requestCode == REQUEST_LAUNCH_IMAGE_CAPTURE) {
final File oldFile = new File(uri.getPath());
final File newDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
final File newFile = new File(newDir.getPath(), uri.getLastPathSegment());
try {
moveFile(oldFile, newFile);
uri = Uri.fromFile(newFile);
} catch (IOException e) {
e.printStackTrace();
responseHelper.putString("error", "Error moving image to camera roll: " + e.getMessage());
}
}
responseHelper.putString("uri", uri.toString());
responseHelper.putString("path", realPath);
if (!noData) {
responseHelper.putString("data", getBase64StringFromFile(realPath));
}
putExtraFileInfo(realPath, responseHelper);
responseHelper.invokeResponse(callback);
callback = null;
this.options = null;
}
use of android.graphics.BitmapFactory.Options in project Resurrection_packages_apps_Settings by ResurrectionRemix.
the class UrlImageViewHelper method loadDrawableFromStream.
private static Drawable loadDrawableFromStream(Context context, String url, String filename, int targetWidth, int targetHeight) {
prepareResources(context);
// Log.v(Constants.LOGTAG,targetHeight);
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream = new FileInputStream(filename);
BitmapFactory.decodeStream(stream, null, o);
stream.close();
stream = new FileInputStream(filename);
int scale = 0;
while ((o.outWidth >> scale) > targetWidth || (o.outHeight >> scale) > targetHeight) {
Log.v(Constants.LOGTAG, "downsampling");
scale++;
}
o = new Options();
o.inSampleSize = 1 << scale;
final Bitmap bitmap = BitmapFactory.decodeStream(stream, null, o);
if (Constants.LOG_ENABLED)
Log.i(Constants.LOGTAG, String.format("Loaded bitmap (%dx%d).", bitmap.getWidth(), bitmap.getHeight()));
BitmapDrawable bd = new BitmapDrawable(mResources, bitmap);
return new ZombieDrawable(url, bd);
} catch (IOException e) {
return null;
}
}
use of android.graphics.BitmapFactory.Options in project AisenWeiBo by wangdan.
the class WallpaperDownloadTask method doDownload.
// 下载壁纸
private File doDownload(File file) throws TaskException {
if (!isRunning())
throw new TaskException("-100", "");
//判断网络是否连接
if (SystemUtils.getNetworkType(GlobalContext.getInstance()) == SystemUtils.NetWorkType.none) {
throw new TaskException("", mContext.getResources().getString(org.aisen.android.R.string.comm_error_noneNetwork));
}
// 先下载一个临时文件
File tempFile = new File(file.getAbsolutePath() + ".tmp");
// 如果图片没有content-length
final int defaultLength = 8 * 1024 * 1024;
// 开始下载图片
try {
total = 0;
progress = 0;
// 发布进度
publishProgress(progress, total);
Logger.d(TAG, "开始下载壁纸 ---> %s", mImageUrl);
Request request = new Request.Builder().get().url(mImageUrl).build();
mCall = httpClient.newCall(request);
Response response = mCall.execute();
if (response == null) {
throw new TaskException(TaskException.TaskError.failIOError.toString());
}
int statusCode = response.code();
if (!(statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_PARTIAL)) {
throw new TaskException(TaskException.TaskError.failIOError.toString());
}
InputStream imageStream = null;
// 写临时文件
FileOutputStream out = new FileOutputStream(tempFile);
try {
String encoding = response.header("Content-Encoding");
if (encoding != null && !TextUtils.isEmpty(encoding) && "gzip".equals(encoding)) {
imageStream = new GZIPInputStream(response.body().byteStream());
Logger.w(TAG, "解压gzip文件, 解压前大小:");
} else {
imageStream = response.body().byteStream();
}
try {
total = response.body().contentLength();
} catch (Exception e) {
// 容错处理,如果未读到大小,默认为8M
total = defaultLength;
}
Logger.d(TAG, "Content-Length = " + total);
if (total < 0)
total = defaultLength;
// 获取图片数据
byte[] buffer = new byte[1024 * 8];
int readLen = -1;
long lastPublishTime = 0l;
while ((readLen = imageStream.read(buffer)) != -1) {
if (!isRunning())
throw new TaskException("-100", "");
progress += readLen;
out.write(buffer, 0, readLen);
Logger.v(TAG, "下载进度, %s / %s", getUnit(progress), getUnit(total));
// 发布进度
long now = System.currentTimeMillis();
if (now - lastPublishTime > PUBLISH_INTERVAL_TIME) {
lastPublishTime = now;
publishProgress(progress, total);
}
}
publishProgress(progress, progress);
Logger.d(TAG, "total : " + total + " readLen : " + readLen);
out.flush();
} catch (IOException e) {
Logger.printExc(WallpaperDownloadTask.class, e);
throw e;
} finally {
out.close();
if (imageStream != null)
imageStream.close();
}
// // 验证一下是否GZip压缩
// try {
// String encoding = response.header("Content-Encoding");
// if (encoding != null && !TextUtils.isEmpty(encoding) &&
// "gzip".equals(encoding)) {
// File ttf = tempFile;
// tempFile = decodeGZipFile(tempFile);
// ttf.delete();
// Logger.w(TAG, "解压gzip文件, 解压前大小:" + total + ", 解压后:" + tempFile.length());
// }
// } catch (Throwable e) {
// Logger.printExc(WallpaperDownloadTask.class, e);
// }
} catch (Throwable e) {
Logger.printExc(WallpaperDownloadTask.class, e);
throw new TaskException("", mContext.getResources().getString(R.string.down_faild));
}
Logger.d(TAG, "File-Length = " + tempFile.length());
Logger.d(TAG, "下载文件成功,path = " + tempFile.getAbsolutePath());
// 重命名之前,对临时文件,做一次图片校验,用BitmapFactory解析一下
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(tempFile.getAbsolutePath(), opts);
// 如果解析的宽高度小于1,默认为非图片
Logger.d(TAG, "图片解析尺寸 %s x %s", opts.outWidth, opts.outHeight);
if (opts.outWidth < 1 && opts.outHeight < 1) {
throw new TaskException("", mContext.getResources().getString(R.string.down_faild));
}
Logger.d(TAG, "下载壁纸完成");
if (!tempFile.renameTo(file))
throw new TaskException("", mContext.getResources().getString(R.string.down_faild));
return file;
}
use of android.graphics.BitmapFactory.Options in project android-app by eoecn.
the class ImageUtil method loadThumbnailImage.
/**
* 从本地或者服务端异步加载缩略图图片
*
* @return
* @param imagePath
* 本地缓存路径
* @param imgUrl
* 拼接后的请求路径
* @param callback
* 得到数据后的处理方法回调
* @throws IOException
*/
public static Bitmap loadThumbnailImage(final String imagePath, final String imgUrl, final DBHelper dbHelper, final ImageCallback callback, final boolean b) {
// 在软链接缓存中,则返回Bitmap对象
if (imageCache.containsKey(imgUrl)) {
SoftReference reference = imageCache.get(imgUrl);
Bitmap bitmap = (Bitmap) reference.get();
if (bitmap != null) {
return bitmap;
}
}
// 若软链接缓存没有
Bitmap bitmap = null;
// 查询数据库 返回bitmap
// 从本地加载
bitmap = getImageFromDB(imagePath, imgUrl, dbHelper);
if (bitmap != null) {
return bitmap;
} else {
// 从网上加载
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.obj != null) {
Bitmap bitmap = (Bitmap) msg.obj;
callback.loadImage(bitmap, imagePath);
}
}
};
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
URL url = new URL(imgUrl);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
InputStream in = conn.getInputStream();
BitmapFactory.Options options = new Options();
options.inSampleSize = 1;
Bitmap bitmap = BitmapFactory.decodeStream(in, new Rect(0, 0, 0, 0), options);
imageCache.put(imgUrl, new SoftReference(bitmap));
Message msg = handler.obtainMessage();
msg.obj = bitmap;
handler.sendMessage(msg);
if (bitmap != null) {
// 保存文件到sd卡
saveImage(imagePath, bitmap);
// 保存到数据库
saveImageByDb(imgUrl, dbHelper);
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(ImageUtil.class.getName(), "图片url不存在");
} catch (IOException e) {
e.printStackTrace();
}
}
};
ThreadPoolManager.getInstance().addTask(runnable);
}
return null;
}
Aggregations