List of usage examples for android.media ExifInterface getAttribute
public String getAttribute(String tag)
From source file:com.wallerlab.compcellscope.Image_Gallery.java
private void writeJsonFile(File[] files) throws JSONException { ExifInterface inter; //Can write meta deta to the JSON File JSONArray image_files = new JSONArray(); for (int i = 0; i < files.length; i++) { File file = files[i];/*from w w w .j a v a 2s . co m*/ JSONObject image = new JSONObject(); String one = file.getName().toString(); Log.d(LOG, "Fileyyyyyy: " + file.getPath()); //Get Information about picture hidden in tags try { inter = new ExifInterface(file.getPath()); Log.d(LOG, "Date Taken: " + inter.getAttribute(ExifInterface.TAG_DATETIME)); Log.d(LOG, "GPSTimeStamp Taken: " + inter.getAttribute(ExifInterface.TAG_GPS_DATESTAMP)); Log.d(LOG, "Make Taken: " + inter.getAttribute(ExifInterface.TAG_MAKE)); } catch (IOException e) { e.printStackTrace(); } Integer.parseInt(one.substring(one.lastIndexOf("(") + 1, one.lastIndexOf(")"))); Integer.parseInt(one.substring(one.lastIndexOf("(") + 1, one.lastIndexOf(")"))); image.put("name", one); image.put("focus", Integer.parseInt(one.substring(one.lastIndexOf("(") + 1, one.lastIndexOf(")")))); image_files.put(image); } try { FileWriter file = new FileWriter(files[0].getParent().toString() + File.separator + "info.json"); file.write("test"); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.plusapp.pocketbiceps.app.MainActivity.java
@TargetApi(Build.VERSION_CODES.N) @Override// w ww . j a v a 2 s.co m protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { // Nach dem man ein Foto mit der Kamera aufgenommen hat wird onActivityResult aufgerufen, bei dem ueberprueft wird ob man das Bild mit Ok oder mit Abbrechen bestaetigt hat case 1: // Wenn nicht auf Abbrechen in der CameraAct. gedrueckt wurde, werden die daten gespeichert // und die AddActivity wird gestartet if (resultCode == RESULT_OK) { SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy-HH-mm-SS"); String dateString = formatter.format(new Date(currTime)); //Speichert das gemachte Bild im path String path = IMAGE_PATH_URI + IMAGE_NAME_PREFIX + dateString + ".jpg"; Drawable.createFromPath(path); Intent intent = new Intent(MainActivity.this, AddActivity.class); // Die currTime Variable wird in die AddActivity weitergegeben, da sie dort als Index benoetigt wird intent.putExtra("currTime", currTime); startActivity(intent); } break; // Bild von der Gallerie importieren case 2: super.onActivityResult(requestCode, resultCode, data); try { // Wenn das Bild ausgewaehlt wurde if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) { // Hole das Bild von data Uri selectedImage = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; String time = ""; long originalTimeInMilli = 0; // Cursor holen Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); // Move to first row cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); imgDecodableString = cursor.getString(columnIndex); cursor.close(); Drawable.createFromPath(imgDecodableString); // Hole das heutige Datum this.currTime = System.currentTimeMillis(); ExifInterface exif = new ExifInterface(imgDecodableString); if (exif != null) { time = exif.getAttribute(ExifInterface.TAG_DATETIME); if (time != null) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd hh:mm:ss"); try { Date mDate = sdf.parse(time); originalTimeInMilli = mDate.getTime(); } catch (ParseException e) { e.printStackTrace(); time = null; } } } Intent intent = new Intent(MainActivity.this, AddActivity.class); if (time == null) { intent.putExtra("currTime", currTime); } else { intent.putExtra("currTime", originalTimeInMilli); } intent.putExtra("pathName", imgDecodableString); intent.putExtra("fromGallery", "true"); startActivity(intent); } else { Toast.makeText(this, R.string.no_pic_chosen, Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show(); } break; } }
From source file:com.google.android.apps.muzei.gallery.GalleryArtSource.java
private void ensureMetadataExists(@NonNull Uri imageUri) { Cursor existingMetadata = getContentResolver().query(GalleryContract.MetadataCache.CONTENT_URI, new String[] { BaseColumns._ID }, GalleryContract.MetadataCache.COLUMN_NAME_URI + "=?", new String[] { imageUri.toString() }, null); if (existingMetadata == null) { return;//www . j a va2 s .c om } boolean metadataExists = existingMetadata.moveToFirst(); existingMetadata.close(); if (!metadataExists) { // No cached metadata or it's stale, need to pull it separately using Exif ContentValues values = new ContentValues(); values.put(GalleryContract.MetadataCache.COLUMN_NAME_URI, imageUri.toString()); InputStream in = null; try { ExifInterface exifInterface; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { in = getContentResolver().openInputStream(imageUri); exifInterface = new ExifInterface(in); } else { File imageFile = GalleryProvider.getLocalFileForUri(this, imageUri); if (imageFile == null) { return; } exifInterface = new ExifInterface(imageFile.getPath()); } String dateString = exifInterface.getAttribute(ExifInterface.TAG_DATETIME); if (!TextUtils.isEmpty(dateString)) { Date date = sExifDateFormat.parse(dateString); values.put(GalleryContract.MetadataCache.COLUMN_NAME_DATETIME, date.getTime()); } float[] latlong = new float[2]; if (exifInterface.getLatLong(latlong)) { // Reverse geocode List<Address> addresses = mGeocoder.getFromLocation(latlong[0], latlong[1], 1); if (addresses != null && addresses.size() > 0) { Address addr = addresses.get(0); String locality = addr.getLocality(); String adminArea = addr.getAdminArea(); String countryCode = addr.getCountryCode(); StringBuilder sb = new StringBuilder(); if (!TextUtils.isEmpty(locality)) { sb.append(locality); } if (!TextUtils.isEmpty(adminArea)) { if (sb.length() > 0) { sb.append(", "); } sb.append(adminArea); } if (!TextUtils.isEmpty(countryCode) && !sOmitCountryCodes.contains(countryCode)) { if (sb.length() > 0) { sb.append(", "); } sb.append(countryCode); } values.put(GalleryContract.MetadataCache.COLUMN_NAME_LOCATION, sb.toString()); } } getContentResolver().insert(GalleryContract.MetadataCache.CONTENT_URI, values); } catch (ParseException e) { Log.w(TAG, "Couldn't read image metadata.", e); } catch (IOException e) { Log.w(TAG, "Couldn't write temporary image file.", e); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } } } }
From source file:org.egov.android.view.activity.CreateComplaintActivity.java
private void _getLatAndLng(String imageUrl) { try {/* ww w .j a v a 2s . c o m*/ double lat = 0.0; double lng = 0.0; ExifInterface exif = new ExifInterface(imageUrl); String attrLatitute = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE); String attrLatituteRef = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF); String attrLONGITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE); String attrLONGITUDEREf = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF); if (attrLatitute == null && attrLONGITUDE == null) { return; } if (attrLatituteRef.equals("N")) { lat = convertToDegree(attrLatitute); } if (attrLONGITUDEREf.equals("E")) { lng = convertToDegree(attrLONGITUDE); } isCurrentLocation = false; _getCurrentLocation(lat, lng); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.annanovas.bestprice.DashBoardEditActivity.java
private Bitmap imageProcess(Bitmap imageBitmap) { int width = imageBitmap.getWidth(); int height = imageBitmap.getHeight(); int newWidth = 1000; int newHeight = 1000; if (width > 1000) { double x = (double) width / 1000d; newHeight = (int) (height / x); newWidth = 1000;/*from w w w . j a v a 2 s . com*/ } else if (height > 1000) { double x = (double) height / 1000d; newWidth = (int) (width / x); newHeight = 1000; } // calculate the scale - in this case = 0.4f ExifInterface exif = null; int rotationAngle = 0; try { exif = new ExifInterface(imageUri); String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION); // showLog("orientString:" + orientString + " DateTime:" + exif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH)); int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL; if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90; if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180; if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270; // showLog("Rotation Angle:" + rotationAngle); } catch (IOException e) { // showLog("ExifInterface Failed!"); e.printStackTrace(); } float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); matrix.postRotate(rotationAngle); return Bitmap.createBitmap(imageBitmap, 0, 0, width, height, matrix, true); }
From source file:mobisocial.bento.ebento.ui.EditFragment.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (DEBUG)/*from w ww . jav a 2s .c o m*/ Log.d(TAG, "requestCode: " + requestCode + ", resultCode: " + resultCode); if (resultCode == Activity.RESULT_OK) { try { File imageFile = null; if (requestCode == REQUEST_IMAGE_CAPTURE) { imageFile = JpgFileHelper.getTmpFile(); } else if (requestCode == REQUEST_GALLERY) { Uri uri = data.getData(); if (uri == null || uri.toString().length() == 0) { return; } if (DEBUG) Log.d(TAG, "data URI: " + uri.toString()); ContentResolver cr = getActivity().getContentResolver(); String[] columns = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME }; Cursor c = cr.query(uri, columns, null, null, null); if (c != null && c.moveToFirst()) { if (c.getString(0) != null) { //regular processing for gallery files imageFile = new File(c.getString(0)); } else { final InputStream is = getActivity().getContentResolver().openInputStream(uri); imageFile = JpgFileHelper.saveTmpFile(is); is.close(); } } else if (uri.toString().startsWith("content://com.android.gallery3d.provider")) { // motorola xoom doesn't work for contentresolver even if the image comes from picasa. // So just adds the condition of startsWith... // See in detail : http://dimitar.me/how-to-get-picasa-images-using-the-image-picker-on-android-devices-running-any-os-version/ uri = Uri.parse( uri.toString().replace("com.android.gallery3d", "com.google.android.gallery3d")); final InputStream is = getActivity().getContentResolver().openInputStream(uri); imageFile = JpgFileHelper.saveTmpFile(is); is.close(); } else { // http or https HttpURLConnection http = null; URL url = new URL(uri.toString()); http = (HttpURLConnection) url.openConnection(); http.setRequestMethod("GET"); http.connect(); final InputStream is = http.getInputStream(); imageFile = JpgFileHelper.saveTmpFile(is); is.close(); if (http != null) http.disconnect(); } } if (imageFile.exists() && imageFile.length() > 0) { if (DEBUG) Log.d(TAG, "imageFile exists=" + imageFile.exists() + " length=" + imageFile.length() + " path=" + imageFile.getPath()); float degrees = 0; try { ExifInterface exif = new ExifInterface(imageFile.getPath()); switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)) { case ExifInterface.ORIENTATION_ROTATE_90: degrees = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degrees = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degrees = 270; break; default: degrees = 0; break; } Log.d(TAG, exif.getAttribute(ExifInterface.TAG_ORIENTATION)); } catch (IOException e) { e.printStackTrace(); } sImageOrg = BitmapHelper.getResizedBitmap(imageFile, BitmapHelper.MAX_IMAGE_WIDTH, BitmapHelper.MAX_IMAGE_HEIGHT, degrees); mbImageChanged = true; // ImageView mImageView.setImageBitmap( BitmapHelper.getResizedBitmap(sImageOrg, mTargetWidth, mTargetHeight, 0)); mImageView.setVisibility(View.VISIBLE); mRootView.invalidate(); imageFile.delete(); JpgFileHelper.deleteTmpFile(); } } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java
/** * Called when the camera view exits./* w w w. j av a 2 s. c o m*/ * * @param requestCode * The request code originally supplied to * startActivityForResult(), allowing you to identify who this * result came from. * @param resultCode * The integer result code returned by the child activity through * its setResult(). * @param intent * An Intent, which can return result data to the caller (various * data can be attached to Intent "extras"). */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { // Get src and dest types from request code int srcType = (requestCode / 16) - 1; int destType = (requestCode % 16) - 1; int rotate = 0; Log.d(LOG_TAG, "-z"); // If retrieving photo from library if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) { Log.d(LOG_TAG, "-y"); if (resultCode == Activity.RESULT_OK) { Log.d(LOG_TAG, "-x"); Uri uri = intent.getData(); Log.d(LOG_TAG, "-w"); // If you ask for video or all media type you will automatically // get back a file URI // and there will be no attempt to resize any returned data if (this.mediaType != PICTURE) { Log.d(LOG_TAG, "mediaType not PICTURE, so must be Video"); String metadataDateTime = ""; ExifInterface exif; try { exif = new ExifInterface(this.getRealPathFromURI(uri, this.cordova)); if (exif.getAttribute(ExifInterface.TAG_DATETIME) != null) { Log.d(LOG_TAG, "z4a"); metadataDateTime = exif.getAttribute(ExifInterface.TAG_DATETIME).toString(); metadataDateTime = metadataDateTime.replaceFirst(":", "-"); metadataDateTime = metadataDateTime.replaceFirst(":", "-"); } } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } Log.d(LOG_TAG, "before create thumbnail"); Bitmap bitmap = ThumbnailUtils.createVideoThumbnail( (new File(this.getRealPathFromURI(uri, this.cordova))).getAbsolutePath(), MediaStore.Images.Thumbnails.MINI_KIND); Log.d(LOG_TAG, "after create thumbnail"); String mid = generateRandomMid(); try { String filePathMedium = this.getTempDirectoryPath(this.cordova.getActivity()) + "/medium_" + mid + ".jpg"; FileOutputStream foMedium = new FileOutputStream(filePathMedium); bitmap.compress(CompressFormat.JPEG, 100, foMedium); foMedium.flush(); foMedium.close(); bitmap.recycle(); System.gc(); JSONObject mediaFile = new JSONObject(); try { mediaFile.put("mid", mid); mediaFile.put("mediaType", "video"); mediaFile.put("filePath", filePathMedium); mediaFile.put("filePathMedium", filePathMedium); mediaFile.put("filePathThumb", filePathMedium); mediaFile.put("typeOfPluginResult", "initialRecordInformer"); String absolutePath = (new File(this.getRealPathFromURI(uri, this.cordova))) .getAbsolutePath(); mediaFile.put("fileExt", absolutePath.substring(absolutePath.lastIndexOf(".") + 1)); if (metadataDateTime != "") { mediaFile.put("metadataDateTime", metadataDateTime); } } catch (JSONException e) { Log.d(LOG_TAG, "error: " + e.getStackTrace().toString()); } Log.d(LOG_TAG, "mediafile at 638" + mediaFile.toString()); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, (new JSONArray()).put(mediaFile)); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); new UploadVideoToS3Task().execute(new File(this.getRealPathFromURI(uri, this.cordova)), this.callbackContext, mid, mediaFile); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } else { String imagePath = this.getRealPathFromURI(uri, this.cordova); String mimeType = FileUtils.getMimeType(imagePath); // If we don't have a valid image so quit. if (imagePath == null || mimeType == null || !(mimeType.equalsIgnoreCase("image/jpeg") || mimeType.equalsIgnoreCase("image/png"))) { Log.d(LOG_TAG, "I either have a null image path or bitmap"); this.failPicture("Unable to retrieve path to picture!"); return; } String mid = generateRandomMid(); Log.d(LOG_TAG, "a"); JSONObject mediaFile = new JSONObject(); Log.d(LOG_TAG, "b"); try { FileInputStream fi = new FileInputStream(imagePath); Bitmap bitmap = BitmapFactory.decodeStream(fi); fi.close(); Log.d(LOG_TAG, "z1"); // try to get exif data ExifInterface exif = new ExifInterface(imagePath); Log.d(LOG_TAG, "z2"); JSONObject metadataJson = new JSONObject(); Log.d(LOG_TAG, "z3"); /* JSONObject latlng = new JSONObject(); String lat = "0"; String lng = "0"; if (exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE) != null) { lat = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE); } if (exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE) != null) { lng = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE); } latlng.put("lat", lat); latlng.put("lng", lng); Log.d(LOG_TAG, "z4"); metadataJson.put("locationData", latlng); */ String metadataDateTime = ""; if (exif.getAttribute(ExifInterface.TAG_DATETIME) != null) { Log.d(LOG_TAG, "z4a"); JSONObject exifWrapper = new JSONObject(); exifWrapper.put("DateTimeOriginal", exif.getAttribute(ExifInterface.TAG_DATETIME).toString()); exifWrapper.put("DateTimeDigitized", exif.getAttribute(ExifInterface.TAG_DATETIME).toString()); metadataDateTime = exif.getAttribute(ExifInterface.TAG_DATETIME).toString(); metadataDateTime = metadataDateTime.replaceFirst(":", "-"); metadataDateTime = metadataDateTime.replaceFirst(":", "-"); Log.d(LOG_TAG, "z5"); metadataJson.put("Exif", exifWrapper); } Log.d(LOG_TAG, "z6"); Log.d(LOG_TAG, "metadataJson: " + metadataJson.toString()); Log.d(LOG_TAG, "metadataDateTime: " + metadataDateTime.toString()); if (exif.getAttribute(ExifInterface.TAG_ORIENTATION) != null) { int o = Integer.parseInt(exif.getAttribute(ExifInterface.TAG_ORIENTATION)); Log.d(LOG_TAG, "z7"); if (o == ExifInterface.ORIENTATION_NORMAL) { rotate = 0; } else if (o == ExifInterface.ORIENTATION_ROTATE_90) { rotate = 90; } else if (o == ExifInterface.ORIENTATION_ROTATE_180) { rotate = 180; } else if (o == ExifInterface.ORIENTATION_ROTATE_270) { rotate = 270; } else { rotate = 0; } Log.d(LOG_TAG, "z8"); Log.d(LOG_TAG, "rotate: " + rotate); // try to correct orientation if (rotate != 0) { Matrix matrix = new Matrix(); Log.d(LOG_TAG, "z9"); matrix.setRotate(rotate); Log.d(LOG_TAG, "z10"); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); Log.d(LOG_TAG, "z11"); } } Log.d(LOG_TAG, "c"); String filePath = this.getTempDirectoryPath(this.cordova.getActivity()) + "/econ_" + mid + ".jpg"; FileOutputStream foEcon = new FileOutputStream(filePath); fitInsideSquare(bitmap, 850).compress(CompressFormat.JPEG, 45, foEcon); foEcon.flush(); foEcon.close(); Log.d(LOG_TAG, "d"); String filePathMedium = this.getTempDirectoryPath(this.cordova.getActivity()) + "/medium_" + mid + ".jpg"; FileOutputStream foMedium = new FileOutputStream(filePathMedium); makeInsideSquare(bitmap, 320).compress(CompressFormat.JPEG, 55, foMedium); foMedium.flush(); foMedium.close(); Log.d(LOG_TAG, "e"); String filePathThumb = this.getTempDirectoryPath(this.cordova.getActivity()) + "/thumb_" + mid + ".jpg"; FileOutputStream foThumb = new FileOutputStream(filePathThumb); makeInsideSquare(bitmap, 175).compress(CompressFormat.JPEG, 55, foThumb); foThumb.flush(); foThumb.close(); bitmap.recycle(); System.gc(); Log.d(LOG_TAG, "f"); mediaFile.put("mid", mid); mediaFile.put("mediaType", "photo"); mediaFile.put("filePath", filePath); mediaFile.put("filePathMedium", filePath); mediaFile.put("filePathThumb", filePath); mediaFile.put("typeOfPluginResult", "initialRecordInformer"); //mediaFile.put("metadataJson", metadataJson); if (metadataDateTime != "") { mediaFile.put("metadataDateTime", metadataDateTime); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, (new JSONArray()).put(mediaFile)); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); Log.d(LOG_TAG, "g"); Log.d(LOG_TAG, "mediaFile " + mediaFile.toString()); new UploadFilesToS3Task().execute(new File(filePath), new File(filePathMedium), new File(filePathThumb), this.callbackContext, mid, mediaFile); Log.d(LOG_TAG, "h"); } catch (FileNotFoundException e) { Log.d(LOG_TAG, "error: " + e.getStackTrace().toString()); } catch (IOException e1) { // TODO Auto-generated catch block Log.d(LOG_TAG, "error: " + e1.getStackTrace().toString()); } catch (JSONException e2) { // TODO Auto-generated catch block Log.d(LOG_TAG, "error: " + e2.getStackTrace().toString()); } /* if (this.correctOrientation) { String[] cols = { MediaStore.Images.Media.ORIENTATION }; Cursor cursor = this.cordova .getActivity() .getContentResolver() .query(intent.getData(), cols, null, null, null); if (cursor != null) { cursor.moveToPosition(0); rotate = cursor.getInt(0); cursor.close(); } if (rotate != 0) { Matrix matrix = new Matrix(); matrix.setRotate(rotate); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } } // Create an ExifHelper to save the exif // data that is lost during compression String resizePath = this .getTempDirectoryPath(this.cordova .getActivity()) + "/resize.jpg"; ExifHelper exif = new ExifHelper(); try { if (this.encodingType == JPEG) { exif.createInFile(resizePath); exif.readExifData(); rotate = exif.getOrientation(); } } catch (IOException e) { e.printStackTrace(); } OutputStream os = new FileOutputStream( resizePath); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); // Restore exif data to file if (this.encodingType == JPEG) { exif.createOutFile(this .getRealPathFromURI(uri, this.cordova)); exif.writeExifData(); } if (bitmap != null) { bitmap.recycle(); bitmap = null; } System.gc(); // The resized image is cached by the app in // order to get around this and not have to // delete your // application cache I'm adding the current // system time to the end of the file url. this.callbackContext.success("file://" + resizePath + "?" + System.currentTimeMillis()); */ } } else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Selection cancelled."); } else { this.failPicture("Selection did not complete!"); } } }
From source file:org.egov.android.view.activity.CreateComplaintActivity.java
public String compressImage(String fromfilepath, String tofilepath) { Bitmap scaledBitmap = null;//www .java2 s . c o m BitmapFactory.Options options = new BitmapFactory.Options(); // by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If // you try the use the bitmap here, you will get null. options.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile(fromfilepath, options); int actualHeight = options.outHeight; int actualWidth = options.outWidth; // max Height and width values of the compressed image is taken as 816x612 float maxHeight = 816.0f; float maxWidth = 612.0f; float imgRatio = actualWidth / actualHeight; float maxRatio = maxWidth / maxHeight; // width and height values are set maintaining the aspect ratio of the image if (actualHeight > maxHeight || actualWidth > maxWidth) { if (imgRatio < maxRatio) { imgRatio = maxHeight / actualHeight; actualWidth = (int) (imgRatio * actualWidth); actualHeight = (int) maxHeight; } else if (imgRatio > maxRatio) { imgRatio = maxWidth / actualWidth; actualHeight = (int) (imgRatio * actualHeight); actualWidth = (int) maxWidth; } else { actualHeight = (int) maxHeight; actualWidth = (int) maxWidth; } } // setting inSampleSize value allows to load a scaled down version of the original image options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight); // inJustDecodeBounds set to false to load the actual bitmap options.inJustDecodeBounds = false; // this options allow android to claim the bitmap memory if it runs low on memory options.inPurgeable = true; options.inInputShareable = true; options.inTempStorage = new byte[16 * 1024]; try { // load the bitmap from its path bmp = BitmapFactory.decodeFile(tofilepath, options); } catch (OutOfMemoryError exception) { exception.printStackTrace(); } try { scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888); } catch (OutOfMemoryError exception) { exception.printStackTrace(); } float ratioX = actualWidth / (float) options.outWidth; float ratioY = actualHeight / (float) options.outHeight; float middleX = actualWidth / 2.0f; float middleY = actualHeight / 2.0f; Matrix scaleMatrix = new Matrix(); scaleMatrix.setScale(ratioX, ratioY, middleX, middleY); Canvas canvas = new Canvas(scaledBitmap); canvas.setMatrix(scaleMatrix); canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG)); String attrLatitute = null; String attrLatituteRef = null; String attrLONGITUDE = null; String attrLONGITUDEREf = null; // check the rotation of the image and display it properly ExifInterface exif; try { exif = new ExifInterface(fromfilepath); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0); Log.d("EXIF", "Exif: " + orientation); Matrix matrix = new Matrix(); if (orientation == 6) { matrix.postRotate(90); Log.d("EXIF", "Exif: " + orientation); } else if (orientation == 3) { matrix.postRotate(180); Log.d("EXIF", "Exif: " + orientation); } else if (orientation == 8) { matrix.postRotate(270); Log.d("EXIF", "Exif: " + orientation); } attrLatitute = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE); attrLatituteRef = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF); attrLONGITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE); attrLONGITUDEREf = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF); scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true); } catch (IOException e) { e.printStackTrace(); } FileOutputStream out = null; try { out = new FileOutputStream(tofilepath); // write the compressed bitmap at the destination specified by filename. scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); ExifInterface exif2 = new ExifInterface(tofilepath); if (attrLatitute != null) { exif2.setAttribute(ExifInterface.TAG_GPS_LATITUDE, attrLatitute); exif2.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, attrLONGITUDE); } if (attrLatituteRef != null) { exif2.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, attrLatituteRef); exif2.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, attrLONGITUDEREf); } exif2.saveAttributes(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return tofilepath; }
From source file:com.aimfire.demo.CameraActivity.java
private void extractCreatorInfo(String path) { ExifInterface exif; try {//from w ww. j a v a 2 s. c o m exif = new ExifInterface(path); /* * TAG_ARTIST and TAG_USER_COMMENT only added in API 24 */ //String creatorName = exif.getAttribute(ExifInterface.TAG_ARTIST); //String creatorPhotoUrl = exif.setAttribute(ExifInterface.TAG_USER_COMMENT); String creatorName = exif.getAttribute("Artist"); String creatorPhotoUrl = exif.getAttribute("UserComment"); if (BuildConfig.DEBUG) Log.e(TAG, "extractCreatorInfo: " + "creatorName=" + creatorName + ", creatorPhotoUrl=" + creatorPhotoUrl); } catch (IOException e) { if (BuildConfig.DEBUG) Log.e(TAG, "extractCreatorInfo: " + e.getMessage()); } }