List of usage examples for android.graphics Bitmap createScaledBitmap
public static Bitmap createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight, boolean filter)
From source file:de.bahnhoefe.deutschlands.bahnhofsfotos.DetailsActivity.java
private void setBitmap(final Bitmap showBitmap) { Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size);//from www. j av a 2s .co m int targetWidth = size.x; if (showBitmap.getWidth() != targetWidth) { Bitmap scaledBitmap = Bitmap.createScaledBitmap(showBitmap, targetWidth, (int) (((long) showBitmap.getHeight() * (long) targetWidth) / showBitmap.getWidth()), true); imageView.setImageBitmap(scaledBitmap); } else { imageView.setImageBitmap(showBitmap); } imageView.setVisibility(View.VISIBLE); invalidateOptionsMenu(); }
From source file:illab.nabal.NabalSimpleDemoActivity.java
/** * Fetch a photo from a remote URL/*from ww w.j a v a 2s . c o m*/ * * @param remotePhotoUrl */ private final void fetchRemotePhoto(final String remotePhotoUrl) { mIsFetchingPhoto = true; showSpinner(); Operation<Delegate, Bitmap> bitmapOp = new Operation<Delegate, Bitmap>() { public void onResult(final Bitmap result) { if (result != null) { //Log.d(TAG, ">>>>>>>>>>>>>> remotePhotoUrl : " + remotePhotoUrl); //Log.d(TAG, ">>>>>>>>>>>>>> result.getWidth() : " + result.getWidth()); //Log.d(TAG, ">>>>>>>>>>>>>> result.getHeight() : " + result.getHeight()); // resize the image if it's too big mTmpImgBitmap = result; if (mTmpImgBitmap.getWidth() > 2000 || mTmpImgBitmap.getHeight() > 2000) { mTmpImgBitmap = Bitmap.createScaledBitmap(mTmpImgBitmap, (int) (mTmpImgBitmap.getWidth() * 0.5F), (int) (mTmpImgBitmap.getHeight() * 0.5F), true); } else if (mTmpImgBitmap.getWidth() > 1000 || mTmpImgBitmap.getHeight() > 1000) { mTmpImgBitmap = Bitmap.createScaledBitmap(mTmpImgBitmap, (int) (mTmpImgBitmap.getWidth() * 0.66F), (int) (mTmpImgBitmap.getHeight() * 0.66F), true); } //Log.d(TAG, ">>>>>>>>>>>>>> mTmpImgBitmap.getWidth() : " + mTmpImgBitmap.getWidth()); //Log.d(TAG, ">>>>>>>>>>>>>> mTmpImgBitmap.getHeight() : " + mTmpImgBitmap.getHeight()); // store the image to a temporary file mDialogHelper.toast("Saving the downloaded image...", Toast.LENGTH_LONG, true); try { StorageHelper.newInstance(NabalSimpleDemoActivity.this).saveBitmap(mTmpImgBitmap, TEMP_IMG_FILE_NAME, Bitmap.CompressFormat.PNG, 90); } catch (Exception e) { onFail(e); return; } // go post this photo with description mTmpImgFilePath = getFilePath(TEMP_IMG_FILE_NAME); mIsFetchingPhoto = false; postPhoto(mTmpImgFilePath, mEditText1.getText().toString()); } } public void onFail(Exception e) { mIsFetchingPhoto = false; toastErrorMessage(e); } public void execute(Delegate networkDelegate) { if (StringHelper.isEmpty(remotePhotoUrl) == false) { networkDelegate.getBitmapFromUrl(this, remotePhotoUrl); } } }; mOpAgent.carryOut(bitmapOp); }
From source file:com.microsoft.projectoxford.face.samples.ui.Camera2BasicFragment.java
private void detectAndFrame() { final Bitmap bm = BitmapFactory .decodeFile(getActivity().getExternalFilesDir(null).getAbsolutePath() + "/pic.jpg"); final Bitmap bitm = Bitmap.createScaledBitmap(bm, bm.getWidth() / 8, bm.getHeight() / 8, true); final Bitmap bn = BitmapFactory .decodeFile(getActivity().getExternalFilesDir(null).getAbsolutePath() + "/pic_l.jpg"); final Bitmap bitn = Bitmap.createScaledBitmap(bn, bn.getWidth() / 8, bn.getHeight() / 8, true); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bitm.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); final AsyncTask<UUID, String, IdentifyResult[]> identifyTask = new AsyncTask<UUID, String, IdentifyResult[]>() { private boolean mSucceed = true; private String mPersonGroupId = getString(R.string.group_id); @Override/*from ww w. j a va 2s . c o m*/ protected IdentifyResult[] doInBackground(UUID... params) { try { // Start identification. return faceServiceClient.identity(this.mPersonGroupId, /* personGroupId */ params, /* faceIds */ 1); /* maxNumOfCandidatesReturned */ } catch (Exception e) { mSucceed = false; return null; } } @Override protected void onPostExecute(IdentifyResult[] result) { // Show the result on screen when detection is done. if (result == null) { showToast("error"); return; } if (result[0].candidates.size() > 0) { showToast("pass"); plu.unlock(); } else { showToast("no such user"); } } }; AsyncTask<InputStream, String, Face[]> detectTask = new AsyncTask<InputStream, String, Face[]>() { @Override protected Face[] doInBackground(InputStream... params) { try { publishProgress("Detecting..."); result = faceServiceClient.detect(params[0], true, // returnFaceId true, // returnFaceLandmarks null // returnFaceAttributes: a string like "age, gender" ); if (result == null) { publishProgress("Detection Finished. Nothing detected"); return null; } publishProgress(String.format("Detection Finished. %d face(s) detected", result.length)); return result; } catch (Exception e) { publishProgress("Detection failed"); return null; } } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(String... progress) { } @Override protected void onPostExecute(Face[] result) { if (result == null || result.length == 0) { showToast("No Face"); return; } if (result.length > 1) { showToast("More than one Face"); return; } if (checkb(bitm, bitn) && checkl(bitm, bitn, result[0].faceLandmarks.eyeLeftOuter.x, result[0].faceLandmarks.eyeLeftTop.y, result[0].faceLandmarks.eyeLeftInner.x, result[0].faceLandmarks.eyeLeftBottom.y) && checkl(bitm, bitn, result[0].faceLandmarks.eyeRightInner.x, result[0].faceLandmarks.eyeRightTop.y, result[0].faceLandmarks.eyeRightOuter.x, result[0].faceLandmarks.eyeRightBottom.y)) { List<UUID> faceIds = new ArrayList<>(); for (Face face : result) { faceIds.add(face.faceId); } identifyTask.execute(faceIds.toArray(new UUID[faceIds.size()])); //showToast("Human"); } else { showToast("Photo"); try { Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getActivity().getApplicationContext(), notification); r.play(); } catch (Exception e) { e.printStackTrace(); } } } }; detectTask.execute(inputStream); }
From source file:com.inter.trade.ui.fragment.agent.AgentApplyFragmentNew.java
private void doPhoto(int requestCode, Intent data) { if (requestCode == SELECT_PIC_BY_PICK_PHOTO) // ?? {//ww w. j a v a 2 s . c om if (data == null) { Toast.makeText(getActivity(), "", Toast.LENGTH_LONG).show(); return; } photoUri = data.getData(); if (photoUri == null) { Toast.makeText(getActivity(), "", Toast.LENGTH_LONG).show(); return; } } String[] pojo = { MediaStore.Images.Media.DATA }; mCursor = getActivity().managedQuery(photoUri, pojo, null, null, null); if (mCursor != null) { int columnIndex = mCursor.getColumnIndexOrThrow(pojo[0]); mCursor.moveToFirst(); picPath = mCursor.getString(columnIndex); // cursor.close(); } if (picPath != null && (picPath.endsWith(".png") || picPath.endsWith(".PNG") || picPath.endsWith(".jpg") || picPath.endsWith(".JPG"))) { try { File file = new File(picPath); FileInputStream inputStream = new FileInputStream(file); Logger.d("file", "length " + inputStream.available()); // inputStream.close(); // BitmapFactory.Options options = new BitmapFactory.Options(); // options.inSampleSize = 4; // Bitmap bm = BitmapFactory.decodeFile(picPath, options); Bitmap bm = decodeSampledBitmapFromDescriptor(inputStream.getFD(), 300, 300, null); if (pos == 0) { agent_applying_license_photo_img.setBackgroundDrawable(null); agent_applying_license_photo_img.setImageBitmap(bm); identityBitmap1 = Bitmap.createScaledBitmap(bm, 200, 300, true); path[0] = picPath; mInfoList.get(agentType).infoDataList.get(pos).putValue("selectpic", "1"); // agent_applying_license_photo_done_img.setVisibility(View.VISIBLE); } else if (pos == 1) { agent_applying_organization_photo_img.setBackgroundDrawable(null); agent_applying_organization_photo_img.setImageBitmap(bm); identityBitmap2 = Bitmap.createScaledBitmap(bm, 200, 300, true); path[1] = picPath; mInfoList.get(agentType).infoDataList.get(pos).putValue("selectpic", "1"); // agent_applying_organization_photo_done_img.setVisibility(View.VISIBLE); } else if (pos == 2) { agent_applying_tax_photo_img.setBackgroundDrawable(null); agent_applying_tax_photo_img.setImageBitmap(bm); identityBitmap3 = Bitmap.createScaledBitmap(bm, 200, 300, true); path[2] = picPath; mInfoList.get(agentType).infoDataList.get(pos).putValue("selectpic", "1"); // agent_applying_tax_photo_done_img.setVisibility(View.VISIBLE); } else if (pos == 3) { agent_applying_id_card_photo_img.setBackgroundDrawable(null); agent_applying_id_card_photo_img.setImageBitmap(bm); identityBitmap4 = Bitmap.createScaledBitmap(bm, 200, 300, true); path[3] = picPath; mInfoList.get(agentType).infoDataList.get(pos).putValue("selectpic", "1"); // agent_applying_id_card_photo_done_img.setVisibility(View.VISIBLE); } isPicChange = true; // agent_applying_license_photo_done_img.setVisibility(View.VISIBLE); } catch (Exception e) { // TODO: handle exception } } else { Toast.makeText(getActivity(), "?", Toast.LENGTH_LONG).show(); } }
From source file:com.concentriclivers.mms.com.android.mms.transaction.MessagingNotification.java
/** * updateNotification is *the* main function for building the actual notification handed to * the NotificationManager/*from w w w. ja va2 s . c om*/ * @param context * @param isNew if we've got a new message, show the ticker * @param uniqueThreadCount */ private static void updateNotification(Context context, boolean isNew, int uniqueThreadCount) { // TDH Log.d("NotificationDebug", "updateNotification()"); // If the user has turned off notifications in settings, don't do any notifying. if (!MessagingPreferenceActivity.getNotificationEnabled(context)) { if (DEBUG) { Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing"); } // TDH Log.d("NotificationDebug", "Notifications not enabled!"); return; } // Figure out what we've got -- whether all sms's, mms's, or a mixture of both. int messageCount = sNotificationSet.size(); // TDH: Log.d("NotificationDebug", "messageCount: " + messageCount); if (messageCount == 0) { Log.d("NotificationDebug", "WTF. Should have at least one message."); return; } NotificationInfo mostRecentNotification = sNotificationSet.first(); // TDH: Use NotificationCompat2 (and in other places but it is obvious where). final NotificationCompat2.Builder noti = new NotificationCompat2.Builder(context) .setWhen(mostRecentNotification.mTimeMillis); if (isNew) { noti.setTicker(mostRecentNotification.mTicker); } // TDH Log.d("NotificationDebug", "Creating TaskStackBuilder"); TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); // TDH Log.d("NotificationDebug", "Created TaskStackBuilder. UniqueThreadCount: " + uniqueThreadCount); // If we have more than one unique thread, change the title (which would // normally be the contact who sent the message) to a generic one that // makes sense for multiple senders, and change the Intent to take the // user to the conversation list instead of the specific thread. // Cases: // 1) single message from single thread - intent goes to ComposeMessageActivity // 2) multiple messages from single thread - intent goes to ComposeMessageActivity // 3) messages from multiple threads - intent goes to ConversationList final Resources res = context.getResources(); String title = null; Bitmap avatar = null; if (uniqueThreadCount > 1) { // messages from multiple threads Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN); mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); mainActivityIntent.setType("vnd.android-dir/mms-sms"); taskStackBuilder.addNextIntent(mainActivityIntent); title = context.getString(R.string.message_count_notification, messageCount); } else { // same thread, single or multiple messages title = mostRecentNotification.mTitle; BitmapDrawable contactDrawable = (BitmapDrawable) mostRecentNotification.mSender.getAvatar(context, null); if (contactDrawable != null) { // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we // have to scale 'em up to 128x128 to fill the whole notification large icon. avatar = contactDrawable.getBitmap(); if (avatar != null) { final int idealIconHeight = res .getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res .getDimensionPixelSize(android.R.dimen.notification_large_icon_width); if (avatar.getHeight() < idealIconHeight) { // Scale this image to fit the intended size avatar = Bitmap.createScaledBitmap(avatar, idealIconWidth, idealIconHeight, true); } if (avatar != null) { noti.setLargeIcon(avatar); } } } taskStackBuilder.addParentStack(ComposeMessageActivity.class); taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent); } // TDH Log.d("NotificationDebug", "title: " + title); // Always have to set the small icon or the notification is ignored noti.setSmallIcon(R.drawable.stat_notify_sms); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Update the notification. noti.setContentTitle(title) .setContentIntent(taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)); // TDH: Can't do these yet. // .addKind(Notification.KIND_MESSAGE) // .setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming // // from a favorite. int defaults = 0; if (isNew) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); String vibrateWhen; if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) { vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null); } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) { vibrateWhen = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false) ? context.getString(R.string.prefDefault_vibrate_true) : context.getString(R.string.prefDefault_vibrate_false); } else { vibrateWhen = context.getString(R.string.prefDefault_vibrateWhen); } boolean vibrateAlways = vibrateWhen.equals("always"); boolean vibrateSilent = vibrateWhen.equals("silent"); AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); boolean nowSilent = audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE; if (vibrateAlways || vibrateSilent && nowSilent) { defaults |= Notification.DEFAULT_VIBRATE; } String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr)); if (DEBUG) { Log.d(TAG, "updateNotification: new message, adding sound to the notification"); } } defaults |= Notification.DEFAULT_LIGHTS; noti.setDefaults(defaults); // set up delete intent noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0)); final Notification notification; if (messageCount == 1) { // We've got a single message // TDH Log.d("NotificationDebug", "Single message, with text: " + mostRecentNotification.formatBigMessage(context)); // This sets the text for the collapsed form: noti.setContentText(mostRecentNotification.formatBigMessage(context)); if (mostRecentNotification.mAttachmentBitmap != null) { // The message has a picture, show that notification = new NotificationCompat2.BigPictureStyle(noti) .bigPicture(mostRecentNotification.mAttachmentBitmap) // This sets the text for the expanded picture form: .setSummaryText(mostRecentNotification.formatPictureMessage(context)).build(); } else { // Show a single notification -- big style with the text of the whole message notification = new NotificationCompat2.BigTextStyle(noti) .bigText(mostRecentNotification.formatBigMessage(context)).build(); } } else { // We've got multiple messages if (uniqueThreadCount == 1) { // We've got multiple messages for the same thread. // Starting with the oldest new message, display the full text of each message. // Begin a line for each subsequent message. SpannableStringBuilder buf = new SpannableStringBuilder(); NotificationInfo infos[] = sNotificationSet.toArray(new NotificationInfo[sNotificationSet.size()]); int len = infos.length; for (int i = len - 1; i >= 0; i--) { NotificationInfo info = infos[i]; buf.append(info.formatBigMessage(context)); if (i != 0) { buf.append('\n'); } } noti.setContentText(context.getString(R.string.message_count_notification, messageCount)); // Show a single notification -- big style with the text of all the messages notification = new NotificationCompat2.BigTextStyle(noti).bigText(buf) // Forcibly show the last line, with the app's smallIcon in it, if we // kicked the smallIcon out with an avatar bitmap .setSummaryText((avatar == null) ? null : " ").build(); } else { // Build a set of the most recent notification per threadId. HashSet<Long> uniqueThreads = new HashSet<Long>(sNotificationSet.size()); ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>(); Iterator<NotificationInfo> notifications = sNotificationSet.iterator(); while (notifications.hasNext()) { NotificationInfo notificationInfo = notifications.next(); if (!uniqueThreads.contains(notificationInfo.mThreadId)) { uniqueThreads.add(notificationInfo.mThreadId); mostRecentNotifPerThread.add(notificationInfo); } } // When collapsed, show all the senders like this: // Fred Flinstone, Barry Manilow, Pete... noti.setContentText(formatSenders(context, mostRecentNotifPerThread)); NotificationCompat2.InboxStyle inboxStyle = new NotificationCompat2.InboxStyle(noti); // We have to set the summary text to non-empty so the content text doesn't show // up when expanded. inboxStyle.setSummaryText(" "); // At this point we've got multiple messages in multiple threads. We only // want to show the most recent message per thread, which are in // mostRecentNotifPerThread. int uniqueThreadMessageCount = mostRecentNotifPerThread.size(); int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount); for (int i = 0; i < maxMessages; i++) { NotificationInfo info = mostRecentNotifPerThread.get(i); inboxStyle.addLine(info.formatInboxMessage(context)); } notification = inboxStyle.build(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification"); } } } // TDH Log.d("NotificationDebug", "Showing notification: " + notification); nm.notify(NOTIFICATION_ID, notification); }
From source file:com.segma.trim.MainActivity.java
private Bitmap getBitmapFromPath() { //BitmapFactory.Options bmOptions = new BitmapFactory.Options(); //bmOptions.inJustDecodeBounds = false; // TODO: UPDATE: Decode bitmap to suitable size to avoid memory issue BitmapFactory.Options option = new BitmapFactory.Options(); option.inJustDecodeBounds = true;//w w w. j a v a 2 s . c o m BitmapFactory.decodeFile(mCurrentPhotoPath, option); double resizeRatio = Math.sqrt((double) SAVE_BITMAP_MAX_PIXEL_SIZE / (option.outWidth * option.outHeight)); int autoHeight = (int) (resizeRatio * option.outHeight); int autoWidth = (int) (resizeRatio * option.outWidth); // Calculate inSampleSize option.inSampleSize = calculateInSampleSize(option, autoWidth, autoHeight); // Decode bitmap with inSampleSize set option.inJustDecodeBounds = false; return Bitmap.createScaledBitmap(BitmapFactory.decodeFile(mCurrentPhotoPath, option), (int) (resizeRatio * option.outWidth), (int) (resizeRatio * option.outHeight), false); }
From source file:com.todoroo.astrid.actfm.sync.ActFmSyncService.java
public static MultipartEntity buildPictureData(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (bitmap.getWidth() > 512 || bitmap.getHeight() > 512) { float scale = Math.min(512f / bitmap.getWidth(), 512f / bitmap.getHeight()); bitmap = Bitmap.createScaledBitmap(bitmap, (int) (scale * bitmap.getWidth()), (int) (scale * bitmap.getHeight()), false); }//from ww w .ja va 2 s . c o m bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos); byte[] bytes = baos.toByteArray(); MultipartEntity data = new MultipartEntity(); data.addPart("picture", new ByteArrayBody(bytes, "image/jpg", "image.jpg")); return data; }
From source file:com.segma.trim.MainActivity.java
private Bitmap compressImgSize2FitIPV(Bitmap bitmap) { int imageHeight = bitmap.getHeight(); int imageWidth = bitmap.getWidth(); // TODO: prevent height or width == 0 even after getting bitmap while (ImageProcessingViewHeight == 0) ;/*w w w . j a v a2 s . c o m*/ return Bitmap.createScaledBitmap(bitmap, ImageProcessingViewHeight * imageWidth / imageHeight, ImageProcessingViewHeight, true); }
From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java
/** * Return a scaled bitmap based on the target width and height * /*from ww w . java 2s . c o m*/ * @param imagePath * @return */ private Bitmap getScaledBitmap(String imagePath) { // If no new width or height were specified return the original bitmap if (this.targetWidth <= 0 && this.targetHeight <= 0) { return BitmapFactory.decodeFile(imagePath); } // figure out the original width and height of the image BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(imagePath, options); // determine the correct aspect ratio int[] widthHeight = calculateAspectRatio(options.outWidth, options.outHeight); // Load in the smallest bitmap possible that is closest to the size we // want options.inJustDecodeBounds = false; options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, this.targetWidth, this.targetHeight); Bitmap unscaledBitmap = BitmapFactory.decodeFile(imagePath, options); if (unscaledBitmap == null) { return null; } return Bitmap.createScaledBitmap(unscaledBitmap, widthHeight[0], widthHeight[1], true); }