List of usage examples for android.graphics Bitmap recycle
public void recycle()
From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java
/** * Called when the camera view exits.//from w w w .jav a2 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:com.phonegap.Capture.java
/** * Called when the video view exits. /*www . j ava 2 s . c om*/ * * @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"). * @throws JSONException */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { // Result received okay if (resultCode == Activity.RESULT_OK) { // An audio clip was requested if (requestCode == CAPTURE_AUDIO) { // Get the uri of the audio clip Uri data = intent.getData(); // create a file object from the uri results.put(createMediaFile(data)); if (results.length() >= limit) { // Send Uri back to JavaScript for listening to audio this.success(new PluginResult(PluginResult.Status.OK, results, "navigator.device.capture._castMediaFile"), this.callbackId); } else { // still need to capture more audio clips captureAudio(); } } else if (requestCode == CAPTURE_IMAGE) { // For some reason if I try to do: // Uri data = intent.getData(); // It crashes in the emulator and on my phone with a null pointer exception // To work around it I had to grab the code from CameraLauncher.java try { // Create an ExifHelper to save the exif data that is lost during compression ExifHelper exif = new ExifHelper(); exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx) + "/Capture.jpg"); exif.readExifData(); // Read in bitmap of captured image Bitmap bitmap = android.provider.MediaStore.Images.Media .getBitmap(this.ctx.getContentResolver(), imageUri); // Create entry in media store for image // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it) ContentValues values = new ContentValues(); values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, IMAGE_JPEG); Uri uri = null; try { uri = this.ctx.getContentResolver() .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException e) { LOG.d(LOG_TAG, "Can't write to external media storage."); try { uri = this.ctx.getContentResolver() .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException ex) { LOG.d(LOG_TAG, "Can't write to internal media storage."); this.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image - no media storage found.")); return; } } // Add compressed version of captured image to returned media store Uri OutputStream os = this.ctx.getContentResolver().openOutputStream(uri); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); os.close(); bitmap.recycle(); bitmap = null; System.gc(); // Restore exif data to file exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx)); exif.writeExifData(); // Add image to results results.put(createMediaFile(uri)); if (results.length() >= limit) { // Send Uri back to JavaScript for viewing image this.success(new PluginResult(PluginResult.Status.OK, results, "navigator.device.capture._castMediaFile"), this.callbackId); } else { // still need to capture more images captureImage(); } } catch (IOException e) { e.printStackTrace(); this.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image.")); } } else if (requestCode == CAPTURE_VIDEO) { // Get the uri of the video clip Uri data = intent.getData(); // create a file object from the uri results.put(createMediaFile(data)); if (results.length() >= limit) { // Send Uri back to JavaScript for viewing video this.success(new PluginResult(PluginResult.Status.OK, results, "navigator.device.capture._castMediaFile"), this.callbackId); } else { // still need to capture more video clips captureVideo(duration); } } } // If canceled else if (resultCode == Activity.RESULT_CANCELED) { // If we have partial results send them back to the user if (results.length() > 0) { this.success(new PluginResult(PluginResult.Status.OK, results, "navigator.device.capture._castMediaFile"), this.callbackId); } // user canceled the action else { this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Canceled.")); } } // If something else else { // If we have partial results send them back to the user if (results.length() > 0) { this.success(new PluginResult(PluginResult.Status.OK, results, "navigator.device.capture._castMediaFile"), this.callbackId); } // something bad happened else { this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Did not complete!")); } } }
From source file:cw.kop.autobackground.files.DownloadThread.java
private void writeToFileWithThumbnail(Bitmap image, String saveData, String dir, File file, long time) { if (file.isFile()) { file.delete();//w ww .java 2 s . c om } FileOutputStream out = null; FileOutputStream thumbnailOut = null; try { int bitWidth = image.getWidth(); int bitHeight = image.getHeight(); float thumbnailSize = (float) AppSettings.getThumbnailSize(); Bitmap thumbnail; if (thumbnailSize < bitWidth && thumbnailSize < bitHeight) { Matrix matrix = new Matrix(); if (bitWidth > bitHeight) { matrix.postScale(thumbnailSize / bitWidth, thumbnailSize / bitWidth); } else { matrix.postScale(thumbnailSize / bitHeight, thumbnailSize / bitHeight); } thumbnail = Bitmap.createBitmap(image, 0, 0, bitWidth, bitHeight, matrix, false); } else { thumbnail = image; } out = new FileOutputStream(file); image.compress(Bitmap.CompressFormat.PNG, 90, out); File thumbnailCache = new File(dir + "/HistoryCache"); if (!thumbnailCache.exists() || (thumbnailCache.exists() && !thumbnailCache.isDirectory())) { thumbnailCache.mkdir(); } File thumbnailFile = new File(thumbnailCache.getAbsolutePath() + "/" + time + ".png"); thumbnailOut = new FileOutputStream(thumbnailFile); thumbnail.compress(Bitmap.CompressFormat.PNG, 90, thumbnailOut); Log.i(TAG, "Thumbnail written: " + thumbnailFile.getAbsolutePath()); AppSettings.setUrl(file.getName(), saveData); Log.i(TAG, file.getName() + " " + saveData); thumbnail.recycle(); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (thumbnailOut != null) { thumbnailOut.close(); } } catch (IOException e) { e.printStackTrace(); } } image.recycle(); }
From source file:com.polyvi.xface.extension.camera.XCameraExt.java
private void cameraSucess(Intent intent) { try {//from w w w. j a v a 2 s . co m Bitmap bitmap = null; try { //???imagebitmap if (mAllowEdit) { //??????Android??? //???URI Bundle extras = intent.getExtras(); if (extras != null) { bitmap = extras.getParcelable("data"); } //?????URI if ((bitmap == null) || (extras == null)) { bitmap = getCroppedBitmap(intent); } } else { // ???? bitmap = android.provider.MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), mImageUri); } } catch (FileNotFoundException e) { Uri uri = intent.getData(); android.content.ContentResolver resolver = getContext().getContentResolver(); bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); } catch (IOException e) { mCallbackCtx.error("Can't open image"); } catch (OutOfMemoryError e) { XNotification notification = new XNotification(mExtensionContext.getSystemContext()); notification.alert("Size of Image is too large!", "Save Image Error", "OK", null, DURATION); mCallbackCtx.error("Size of image is too large"); return; } // ??? Bitmap scaleBitmap = scaleBitmap(bitmap); Uri uri = null; if (mDestType == DATA_URL) { processPicture(scaleBitmap); checkForDuplicateImage(DATA_URL); } else if (mDestType == FILE_URI || mDestType == NATIVE_URI) { if (!this.mSaveToPhotoAlbum) { String suffixName = null; if (mEncodingType == JPEG) { suffixName = ".jpg"; } else if (mEncodingType == PNG) { suffixName = ".png"; } else { throw new IllegalArgumentException("Invalid Encoding Type: " + mEncodingType); } String photoName = System.currentTimeMillis() + suffixName; uri = Uri.fromFile(new File(mWebContext.getWorkSpace(), photoName)); } else { uri = getUriFromMediaStore(); } if (uri == null) { mCallbackCtx.error("Error capturing image - no media storage found."); } // ? OutputStream os = getContext().getContentResolver().openOutputStream(uri); scaleBitmap.compress(Bitmap.CompressFormat.JPEG, mQuality, os); os.close(); // ??success callback XPathResolver pathResolver = new XPathResolver(uri.toString(), "", getContext()); mCallbackCtx.success(XConstant.FILE_SCHEME + pathResolver.resolve()); } scaleBitmap.recycle(); scaleBitmap = null; cleanup(FILE_URI, mImageUri, uri, bitmap); } catch (IOException e) { mCallbackCtx.error("Error capturing image."); } }
From source file:com.entertailion.android.overlaynews.Downloader.java
private synchronized void updateFeeds() { Log.d(LOG_TAG, "updateFeeds"); updateTime = System.currentTimeMillis(); try {/*from w w w . java2s.c o m*/ // iterate through feeds in database ArrayList<RssFeed> feeds = FeedsTable.getFeeds(context); Log.d(LOG_TAG, "feeds=" + feeds); if (feeds != null) { for (RssFeed feed : feeds) { // Check if TTL set for feed if (feed.getTtl() != -1) { if (System.currentTimeMillis() - (feed.getDate().getTime() + feed.getTtl() * 60 * 1000) < 0) { // too soon Log.d(LOG_TAG, "TTL not reached: " + feed.getTitle()); break; } } String rss = Utils.getRssFeed(feed.getLink(), context, true); RssHandler rh = new RssHandler(); RssFeed rssFeed = rh.getFeed(rss); if (rssFeed.getTitle() == null) { try { Uri uri = Uri.parse(feed.getLink()); rssFeed.setTitle(uri.getHost()); } catch (Exception e) { Log.e(LOG_TAG, "get host", e); } } Uri uri = Uri.parse(feed.getLink()); Log.d(LOG_TAG, "host=" + uri.getScheme() + "://" + uri.getHost()); String icon = Utils.getWebSiteIcon(context, "http://" + uri.getHost()); Log.d(LOG_TAG, "icon1=" + icon); if (icon == null) { // try base host address int count = StringUtils.countMatches(uri.getHost(), "."); if (count > 1) { int index = uri.getHost().indexOf('.'); String baseHost = uri.getHost().substring(index + 1); icon = Utils.getWebSiteIcon(context, "http://" + baseHost); Log.d(LOG_TAG, "icon2=" + icon); } } if (icon != null) { try { FileInputStream fis = context.openFileInput(icon); Bitmap bitmap = BitmapFactory.decodeStream(fis); fis.close(); rssFeed.setImage(icon); rssFeed.setBitmap(bitmap); } catch (Exception e) { Log.d(LOG_TAG, "updateFeeds", e); } } if (rssFeed.getBitmap() == null && rssFeed.getLogo() != null) { Log.d(LOG_TAG, "logo=" + rssFeed.getLogo()); Bitmap bitmap = Utils.getBitmapFromURL(rssFeed.getLogo()); if (bitmap != null) { icon = Utils.WEB_SITE_ICON_PREFIX + Utils.clean(rssFeed.getLogo()) + ".png"; Utils.saveToFile(context, bitmap, bitmap.getWidth(), bitmap.getHeight(), icon); rssFeed.setImage(icon); rssFeed.setBitmap(bitmap); } } // update database long time = 0; if (rssFeed.getDate() != null) { time = rssFeed.getDate().getTime(); } FeedsTable.updateFeed(context, feed.getId(), rssFeed.getTitle(), feed.getLink(), rssFeed.getDescription(), time, rssFeed.getViewDate().getTime(), rssFeed.getLogo(), rssFeed.getImage(), rssFeed.getTtl()); ItemsTable.deleteItems(context, feed.getId()); for (RssItem item : rssFeed.getItems()) { if (item.getTitle() != null) { time = 0; if (item.getDate() != null) { time = item.getDate().getTime(); } ItemsTable.insertItem(context, feed.getId(), item.getTitle(), item.getLink(), item.getDescription(), item.getContent(), time); } } // release resources Bitmap bitmap = rssFeed.getBitmap(); if (bitmap != null) { rssFeed.setBitmap(null); bitmap.recycle(); bitmap = null; } } } } catch (Exception e) { Log.e(LOG_TAG, "updateFeeds", e); } }
From source file:com.phonegap.CameraLauncher.java
/** * Called when the camera view exits. //ww w . jav a 2s. 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; // If CAMERA if (srcType == CAMERA) { // If image available if (resultCode == Activity.RESULT_OK) { try { // Read in bitmap of captured image Bitmap bitmap = android.provider.MediaStore.Images.Media .getBitmap(this.ctx.getContentResolver(), imageUri); // If sending base64 image back if (destType == DATA_URL) { this.processPicture(bitmap); } // If sending filename back else if (destType == FILE_URI) { // Create entry in media store for image // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it) ContentValues values = new ContentValues(); values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri = null; try { uri = this.ctx.getContentResolver() .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException e) { System.out.println("Can't write to external media storage."); try { uri = this.ctx.getContentResolver().insert( android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException ex) { System.out.println("Can't write to internal media storage."); this.failPicture("Error capturing image - no media storage found."); return; } } // Add compressed version of captured image to returned media store Uri OutputStream os = this.ctx.getContentResolver().openOutputStream(uri); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); // Send Uri back to JavaScript for viewing image this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } bitmap.recycle(); bitmap = null; System.gc(); } catch (IOException e) { e.printStackTrace(); this.failPicture("Error capturing image."); } } // If cancelled else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Camera cancelled."); } // If something else else { this.failPicture("Did not complete!"); } } // If retrieving photo from library else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) { if (resultCode == Activity.RESULT_OK) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.ctx.getContentResolver(); // If sending base64 image back if (destType == DATA_URL) { try { Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); this.processPicture(bitmap); bitmap.recycle(); bitmap = null; System.gc(); } catch (FileNotFoundException e) { e.printStackTrace(); this.failPicture("Error retrieving image."); } } // If sending filename back else if (destType == FILE_URI) { this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } } else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Selection cancelled."); } else { this.failPicture("Selection did not complete!"); } } }
From source file:app.view.chat.ChatActivity.java
/** * onActivityResult// w w w . j a v a 2 s . c om */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_CODE_EXIT_GROUP) { setResult(RESULT_OK); finish(); return; } if (requestCode == REQUEST_CODE_CONTEXT_MENU) { switch (resultCode) { case RESULT_CODE_COPY: // ?? EMMessage copyMsg = ((EMMessage) adapter.getItem(data.getIntExtra("position", -1))); if (copyMsg.getType() == EMMessage.Type.IMAGE) { ImageMessageBody imageBody = (ImageMessageBody) copyMsg.getBody(); // ??? clipboard.setText(COPY_IMAGE + imageBody.getLocalUrl()); } else { // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this, // ((TextMessageBody) copyMsg.getBody()).getMessage())); clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage()); } break; case RESULT_CODE_DELETE: // ? EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1)); conversation.removeMessage(deleteMsg.getMsgId()); adapter.refresh(); listView.setSelection(data.getIntExtra("position", adapter.getCount()) - 1); break; case RESULT_CODE_FORWARD: // ?? EMMessage forwardMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", 0)); Intent intent = new Intent(this, ForwardMessageActivity.class); intent.putExtra("forward_msg_id", forwardMsg.getMsgId()); startActivity(intent); break; default: break; } } if (resultCode == RESULT_OK) { // ? if (requestCode == REQUEST_CODE_EMPTY_HISTORY) { // ? EMChatManager.getInstance().clearConversation(toChatUsername); adapter.refresh(); } else if (requestCode == REQUEST_CODE_CAMERA) { // ?? if (cameraFile != null && cameraFile.exists()) sendPicture(cameraFile.getAbsolutePath()); } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // ?? int duration = data.getIntExtra("dur", 0); String videoPath = data.getStringExtra("path"); File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis()); Bitmap bitmap = null; FileOutputStream fos = null; try { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3); if (bitmap == null) { EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon"); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.app_panel_video_icon); } fos = new FileOutputStream(file); bitmap.compress(CompressFormat.JPEG, 100, fos); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } fos = null; } if (bitmap != null) { bitmap.recycle(); bitmap = null; } } sendVideo(videoPath, file.getAbsolutePath(), duration / 1000); } else if (requestCode == REQUEST_CODE_LOCAL) { // ?? if (data != null) { Uri selectedImage = data.getData(); if (selectedImage != null) { sendPicByUri(selectedImage); } } } else if (requestCode == REQUEST_CODE_SELECT_FILE) { // ?? if (data != null) { Uri uri = data.getData(); if (uri != null) { sendFile(uri); } } } else if (requestCode == REQUEST_CODE_MAP) { // double latitude = data.getDoubleExtra("latitude", 0); double longitude = data.getDoubleExtra("longitude", 0); String locationAddress = data.getStringExtra("address"); if (locationAddress != null && !locationAddress.equals("")) { more(more); sendLocationMsg(latitude, longitude, "", locationAddress); } else { Toast.makeText(this, "????", Toast.LENGTH_SHORT).show(); } // ??? } else if (requestCode == REQUEST_CODE_TEXT) { resendMessage(); } else if (requestCode == REQUEST_CODE_VOICE) { resendMessage(); } else if (requestCode == REQUEST_CODE_PICTURE) { resendMessage(); } else if (requestCode == REQUEST_CODE_LOCATION) { resendMessage(); } else if (requestCode == REQUEST_CODE_VIDEO || requestCode == REQUEST_CODE_FILE) { resendMessage(); } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) { // if (!TextUtils.isEmpty(clipboard.getText())) { String pasteText = clipboard.getText().toString(); if (pasteText.startsWith(COPY_IMAGE)) { // ??path sendPicture(pasteText.replace(COPY_IMAGE, "")); } } } else if (requestCode == REQUEST_CODE_ADD_TO_BLACKLIST) { // ??? EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1)); addUserToBlacklist(deleteMsg.getFrom()); } else if (conversation.getMsgCount() > 0) { adapter.refresh(); setResult(RESULT_OK); } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) { adapter.refresh(); } } }
From source file:com.almalence.opencam.SavingService.java
protected void addTimestamp(File file, int exif_orientation) { try {/*from w w w. j a v a2s . c o m*/ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); int dateFormat = Integer.parseInt(prefs.getString(ApplicationScreen.sTimestampDate, "0")); boolean abbreviation = prefs.getBoolean(ApplicationScreen.sTimestampAbbreviation, false); int saveGeo = Integer.parseInt(prefs.getString(ApplicationScreen.sTimestampGeo, "0")); int timeFormat = Integer.parseInt(prefs.getString(ApplicationScreen.sTimestampTime, "0")); int separator = Integer.parseInt(prefs.getString(ApplicationScreen.sTimestampSeparator, "0")); String customText = prefs.getString(ApplicationScreen.sTimestampCustomText, ""); int color = Integer.parseInt(prefs.getString(ApplicationScreen.sTimestampColor, "1")); int fontSizeC = Integer.parseInt(prefs.getString(ApplicationScreen.sTimestampFontSize, "80")); String formattedCurrentDate = ""; if (dateFormat == 0 && timeFormat == 0 && customText.equals("") && saveGeo == 0) return; String geoText = ""; // show geo data on time stamp if (saveGeo != 0) { Location l = MLocation.getLocation(getApplicationContext()); if (l != null) { if (saveGeo == 2) { Geocoder geocoder = new Geocoder(MainScreen.getMainContext(), Locale.getDefault()); List<Address> list = geocoder.getFromLocation(l.getLatitude(), l.getLongitude(), 1); if (!list.isEmpty()) { String country = list.get(0).getCountryName(); String locality = list.get(0).getLocality(); String adminArea = list.get(0).getSubAdminArea();// city // localized String street = list.get(0).getThoroughfare();// street // localized String address = list.get(0).getAddressLine(0); // replace street and city with localized name if (street != null) address = street; if (adminArea != null) locality = adminArea; geoText = (country != null ? country : "") + (locality != null ? (", " + locality) : "") + (address != null ? (", \n" + address) : ""); if (geoText.equals("")) geoText = "lat:" + l.getLatitude() + "\nlng:" + l.getLongitude(); } } else geoText = "lat:" + l.getLatitude() + "\nlng:" + l.getLongitude(); } } String dateFormatString = ""; String timeFormatString = ""; String separatorString = "."; String monthString = abbreviation ? "MMMM" : "MM"; switch (separator) { case 0: separatorString = "/"; break; case 1: separatorString = "."; break; case 2: separatorString = "-"; break; case 3: separatorString = " "; break; default: separatorString = " "; } switch (dateFormat) { case 1: dateFormatString = "yyyy" + separatorString + monthString + separatorString + "dd"; break; case 2: dateFormatString = "dd" + separatorString + monthString + separatorString + "yyyy"; break; case 3: dateFormatString = monthString + separatorString + "dd" + separatorString + "yyyy"; break; default: } switch (timeFormat) { case 1: timeFormatString = " hh:mm:ss a"; break; case 2: timeFormatString = " HH:mm:ss"; break; default: } Date currentDate = Calendar.getInstance().getTime(); java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat( dateFormatString + timeFormatString); formattedCurrentDate = simpleDateFormat.format(currentDate); formattedCurrentDate += (customText.isEmpty() ? "" : ("\n" + customText)) + (geoText.isEmpty() ? "" : ("\n" + geoText)); if (formattedCurrentDate.equals("")) return; Bitmap sourceBitmap; Bitmap bitmap; int rotation = 0; Matrix matrix = new Matrix(); if (exif_orientation == ExifInterface.ORIENTATION_ROTATE_90) { rotation = 90; } else if (exif_orientation == ExifInterface.ORIENTATION_ROTATE_180) { rotation = 180; } else if (exif_orientation == ExifInterface.ORIENTATION_ROTATE_270) { rotation = 270; } matrix.postRotate(rotation); BitmapFactory.Options options = new BitmapFactory.Options(); options.inMutable = true; sourceBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options); bitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), matrix, false); sourceBitmap.recycle(); int width = bitmap.getWidth(); int height = bitmap.getHeight(); Paint p = new Paint(); Canvas canvas = new Canvas(bitmap); final float scale = getResources().getDisplayMetrics().density; p.setColor(Color.WHITE); switch (color) { case 0: color = Color.BLACK; p.setColor(Color.BLACK); break; case 1: color = Color.WHITE; p.setColor(Color.WHITE); break; case 2: color = Color.YELLOW; p.setColor(Color.YELLOW); break; } if (width > height) { p.setTextSize(height / fontSizeC * scale + 0.5f); // convert dps // to pixels } else { p.setTextSize(width / fontSizeC * scale + 0.5f); // convert dps // to pixels } p.setTextAlign(Align.RIGHT); drawTextWithBackground(canvas, p, formattedCurrentDate, color, Color.BLACK, width, height); Matrix matrix2 = new Matrix(); matrix2.postRotate(360 - rotation); sourceBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix2, false); bitmap.recycle(); FileOutputStream outStream; outStream = new FileOutputStream(file); sourceBitmap.compress(Bitmap.CompressFormat.JPEG, jpegQuality, outStream); sourceBitmap.recycle(); outStream.flush(); outStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } }
From source file:cn.kangeqiu.kq.activity.ChatOldActivity.java
/** * onActivityResult//from w w w . j a v a 2 s . co m */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_CODE_EXIT_GROUP) { setResult(RESULT_OK); finish(); return; } if (requestCode == REQUEST_CODE_CONTEXT_MENU) { switch (resultCode) { case RESULT_CODE_COPY: // ?? EMMessage copyMsg = ((EMMessage) adapter.getItem(data.getIntExtra("position", -1))); if (copyMsg.getType() == EMMessage.Type.IMAGE) { ImageMessageBody imageBody = (ImageMessageBody) copyMsg.getBody(); // ??? clipboard.setText(COPY_IMAGE + imageBody.getLocalUrl()); } else { // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this, // ((TextMessageBody) copyMsg.getBody()).getMessage())); clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage()); } break; case RESULT_CODE_DELETE: // ? EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1)); conversation.removeMessage(deleteMsg.getMsgId()); adapter.refresh(); listView.setSelection(data.getIntExtra("position", adapter.getCount()) - 1); break; case RESULT_CODE_FORWARD: // ?? EMMessage forwardMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", 0)); Intent intent = new Intent(this, ForwardMessageActivity.class); intent.putExtra("forward_msg_id", forwardMsg.getMsgId()); startActivity(intent); break; default: break; } } if (resultCode == RESULT_OK) { // ? if (requestCode == REQUEST_CODE_EMPTY_HISTORY) { // ? EMChatManager.getInstance().clearConversation(toChatUsername); adapter.refresh(); } else if (requestCode == REQUEST_CODE_CAMERA) { // ?? if (cameraFile != null && cameraFile.exists()) sendPicture(cameraFile.getAbsolutePath()); } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // ?? int duration = data.getIntExtra("dur", 0); String videoPath = data.getStringExtra("path"); File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis()); Bitmap bitmap = null; FileOutputStream fos = null; try { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3); if (bitmap == null) { EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon"); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.app_panel_video_icon); } fos = new FileOutputStream(file); bitmap.compress(CompressFormat.JPEG, 100, fos); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } fos = null; } if (bitmap != null) { bitmap.recycle(); bitmap = null; } } sendVideo(videoPath, file.getAbsolutePath(), duration / 1000); } else if (requestCode == REQUEST_CODE_LOCAL) { // ?? if (data != null) { Uri selectedImage = data.getData(); if (selectedImage != null) { sendPicByUri(selectedImage); } } } else if (requestCode == REQUEST_CODE_SELECT_FILE) { // ?? if (data != null) { Uri uri = data.getData(); if (uri != null) { sendFile(uri); } } } else if (requestCode == REQUEST_CODE_MAP) { // double latitude = data.getDoubleExtra("latitude", 0); double longitude = data.getDoubleExtra("longitude", 0); String locationAddress = data.getStringExtra("address"); if (locationAddress != null && !locationAddress.equals("")) { more(more); sendLocationMsg(latitude, longitude, "", locationAddress); } else { String st4 = getResources().getString(R.string.unable_to_get_loaction); Toast.makeText(this, st4, 0).show(); } // ??? } else if (requestCode == REQUEST_CODE_TEXT) { resendMessage(); } else if (requestCode == REQUEST_CODE_VOICE) { resendMessage(); } else if (requestCode == REQUEST_CODE_PICTURE) { resendMessage(); } else if (requestCode == REQUEST_CODE_LOCATION) { resendMessage(); } else if (requestCode == REQUEST_CODE_VIDEO || requestCode == REQUEST_CODE_FILE) { resendMessage(); } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) { // if (!TextUtils.isEmpty(clipboard.getText())) { String pasteText = clipboard.getText().toString(); if (pasteText.startsWith(COPY_IMAGE)) { // ??path sendPicture(pasteText.replace(COPY_IMAGE, "")); } } } else if (requestCode == REQUEST_CODE_ADD_TO_BLACKLIST) { // ??? EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1)); addUserToBlacklist(deleteMsg.getFrom()); } else if (conversation.getMsgCount() > 0) { adapter.refresh(); setResult(RESULT_OK); } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) { adapter.refresh(); } } }
From source file:com.blueshit.activity.ChatActivity.java
/** * onActivityResult// ww w. j a v a 2 s . com */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_CODE_EXIT_GROUP) { setResult(RESULT_OK); finish(); return; } if (requestCode == REQUEST_CODE_CONTEXT_MENU) { switch (resultCode) { case RESULT_CODE_COPY: // ?? EMMessage copyMsg = ((EMMessage) adapter.getItem(data.getIntExtra("position", -1))); // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this, // ((TextMessageBody) copyMsg.getBody()).getMessage())); clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage()); break; case RESULT_CODE_DELETE: // ? EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1)); conversation.removeMessage(deleteMsg.getMsgId()); adapter.refresh(); listView.setSelection(data.getIntExtra("position", adapter.getCount()) - 1); break; case RESULT_CODE_FORWARD: // ?? // EMMessage forwardMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", 0)); // Intent intent = new Intent(this, ForwardMessageActivity.class); // intent.putExtra("forward_msg_id", forwardMsg.getMsgId()); // startActivity(intent); break; default: break; } } if (resultCode == RESULT_OK) { // ? if (requestCode == REQUEST_CODE_EMPTY_HISTORY) { // ? EMChatManager.getInstance().clearConversation(toChatUsername); adapter.refresh(); } else if (requestCode == REQUEST_CODE_CAMERA) { // ?? if (cameraFile != null && cameraFile.exists()) sendPicture(cameraFile.getAbsolutePath()); } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // ?? int duration = data.getIntExtra("dur", 0); String videoPath = data.getStringExtra("path"); File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis()); Bitmap bitmap = null; FileOutputStream fos = null; try { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3); if (bitmap == null) { EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon"); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.app_panel_video_icon); } fos = new FileOutputStream(file); bitmap.compress(CompressFormat.JPEG, 100, fos); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } fos = null; } if (bitmap != null) { bitmap.recycle(); bitmap = null; } } sendVideo(videoPath, file.getAbsolutePath(), duration / 1000); } else if (requestCode == REQUEST_CODE_LOCAL) { // ?? if (data != null) { Uri selectedImage = data.getData(); if (selectedImage != null) { sendPicByUri(selectedImage); } } } else if (requestCode == REQUEST_CODE_SELECT_FILE) { // ?? if (data != null) { Uri uri = data.getData(); if (uri != null) { sendFile(uri); } } } else if (requestCode == REQUEST_CODE_MAP) { // double latitude = data.getDoubleExtra("latitude", 0); double longitude = data.getDoubleExtra("longitude", 0); String locationAddress = data.getStringExtra("address"); if (locationAddress != null && !locationAddress.equals("")) { more(more); sendLocationMsg(latitude, longitude, "", locationAddress); } else { String st = getResources().getString(R.string.unable_to_get_loaction); Toast.makeText(this, st, Toast.LENGTH_SHORT).show(); } // ??? } else if (requestCode == REQUEST_CODE_TEXT || requestCode == REQUEST_CODE_VOICE || requestCode == REQUEST_CODE_PICTURE || requestCode == REQUEST_CODE_LOCATION || requestCode == REQUEST_CODE_VIDEO || requestCode == REQUEST_CODE_FILE) { resendMessage(); } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) { // if (!TextUtils.isEmpty(clipboard.getText())) { String pasteText = clipboard.getText().toString(); if (pasteText.startsWith(COPY_IMAGE)) { // ??path sendPicture(pasteText.replace(COPY_IMAGE, "")); } } } else if (requestCode == REQUEST_CODE_ADD_TO_BLACKLIST) { // ??? EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1)); addUserToBlacklist(deleteMsg.getFrom()); } else if (conversation.getMsgCount() > 0) { adapter.refresh(); setResult(RESULT_OK); } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) { adapter.refresh(); } } }