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.stadtrallye.rallyesoft.services.UploadService.java
private void upload(final PictureManager.Picture picture, boolean previewUpload) { final int biteSize = 8192 * 4; FileInputStream fileInputStream = null; picture.uploading();/* w w w . j av a 2s. co m*/ try { Uri uri = Uri.parse(picture.getUri()); Log.d(THIS, "Source: " + picture.getUri()); initReport(picture, biteSize); long fileSize = -1; try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && picture.getUri().startsWith("content://")) { // Check for the freshest data. persistUriPermissionApi19(uri); } AssetFileDescriptor fileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r"); fileSize = fileDescriptor.getDeclaredLength();//TODO report as indeterminate progress if length unknown fileInputStream = fileDescriptor.createInputStream(); } catch (SecurityException e) { Log.e(THIS, "No access rights... WTF", e); return; } TypedOutput uploadStream; RetroAuthCommunicator comm = Server.getCurrentServer().getAuthCommunicator(); Picture responsePicture; final long picSize = fileSize; reportUploadBegins(picSize, biteSize); final FileInputStream fIn = fileInputStream; if (previewUpload) { Bitmap img = BitmapFactory.decodeStream(fileInputStream); int biggerSide = (img.getWidth() > img.getHeight()) ? img.getWidth() : img.getHeight(); double factor = PictureSize.Preview.getDimension().height * 1.0 / biggerSide; int w = (int) Math.round(img.getWidth() * factor); int h = (int) Math.round(img.getHeight() * factor); final Bitmap scaled = Bitmap.createScaledBitmap(img, w, h, true); Log.i(THIS, "scaled bitmap. it now is " + w + "x" + h); uploadStream = new TypedOutput() { @Override public String fileName() { return picture.getHash(); } @Override public String mimeType() { return "image/jpeg"; } @Override public long length() { return -1; } @Override public void writeTo(OutputStream out) throws IOException { scaled.compress(Bitmap.CompressFormat.JPEG, 80, out); } }; reportUploadIndeterminate(picture); responsePicture = comm.uploadPreviewPicture(picture.getHash(), uploadStream); picture.uploadedPreview(); } else { uploadStream = new TypedOutput() { @Override public String fileName() { return picture.getHash(); } @Override public String mimeType() { return picture.getMimeType(); } @Override public long length() { return picSize; } @Override public void writeTo(OutputStream out) throws IOException { final byte[] buf = new byte[biteSize]; int readSize = 0; int i = 0; while (readSize >= 0) { readSize = fIn.read(buf); out.write(buf); i++; reportUploadProgress(picture, i); } } }; responsePicture = comm.uploadPicture(picture.getHash(), uploadStream); picture.uploaded(); } if (responsePicture != null) { if (!responsePicture.pictureHash.equals(picture.getHash())) { //TODO picture.serverResponse(responsePicture), possibly rename file / hash, if the server would like to Log.w(THIS, "The server responded with a different hash than it was asked for... We should rename our file, but cannot since it is not yet implemented"); } } reportUploadComplete(picture); Log.i(THIS, "Picture " + picture.pictureID + " successfully uploaded (" + picSize + " bytes)"); return; } catch (RetrofitError e) { if (e.isNetworkError()) { Log.e(THIS, "Retrofit Network error", e.getCause()); } else { Log.e(THIS, "Server declined", e); } } catch (FileNotFoundException e) { Log.e(THIS, "File was not were it was supposed to be: " + picture.getUri(), e); picture.discard(); return; } catch (IOException e) { Log.e(THIS, "Upload failed", e); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } picture.failed(); reportUploadFailure(picture); }
From source file:mobisocial.musubi.util.UriImage.java
/** * Returns the bytes for this UriImage. If the uri for the image is remote, * then this code must not be run on the main thread. *//*from ww w . j a va 2 s . c om*/ public byte[] getResizedImageData(int widthLimit, int heightLimit, int byteLimit, boolean square) throws IOException { if (!mDecodedBounds) { decodeBoundsInfo(); mDecodedBounds = true; } InputStream input = null; try { int inDensity = 0; int targetDensity = 0; BitmapFactory.Options read_options = new BitmapFactory.Options(); read_options.inJustDecodeBounds = true; input = openInputStream(mUri); BitmapFactory.decodeStream(input, null, read_options); if (read_options.outWidth > widthLimit || read_options.outHeight > heightLimit) { //we need to scale if (read_options.outWidth / widthLimit > read_options.outHeight / heightLimit) { //width is the large edge if (read_options.outWidth * heightLimit > widthLimit * read_options.outHeight) { //incoming image is wider than target inDensity = read_options.outWidth; targetDensity = widthLimit; } else { //incoming image is taller than target inDensity = read_options.outHeight; targetDensity = heightLimit; } } else { //height is the long edge, swap the limits if (read_options.outWidth * widthLimit > heightLimit * read_options.outHeight) { //incoming image is wider than target inDensity = read_options.outWidth; targetDensity = heightLimit; } else { //incoming image is taller than target inDensity = read_options.outHeight; targetDensity = widthLimit; } } } else { //no scale if (read_options.outWidth > read_options.outHeight) { inDensity = targetDensity = read_options.outWidth; } else { inDensity = targetDensity = read_options.outHeight; } } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "getResizedImageData: wlimit=" + widthLimit + ", hlimit=" + heightLimit + ", sizeLimit=" + byteLimit + ", mWidth=" + mWidth + ", mHeight=" + mHeight + ", initialRatio=" + targetDensity + "/" + inDensity); } ByteArrayOutputStream os = null; int attempts = 1; int lowMemoryReduce = 1; do { BitmapFactory.Options options = new BitmapFactory.Options(); options.inDensity = inDensity; options.inSampleSize = lowMemoryReduce; options.inScaled = lowMemoryReduce == 1; options.inTargetDensity = targetDensity; //no purgeable because we are only trying to resave this if (input != null) input.close(); input = openInputStream(mUri); int quality = IMAGE_COMPRESSION_QUALITY; try { Bitmap b = BitmapFactory.decodeStream(input, null, options); if (b == null) { return null; } if (options.outWidth > widthLimit + 1 || options.outHeight > heightLimit + 1) { // The decoder does not support the inSampleSize option. // Scale the bitmap using Bitmap library. int scaledWidth; int scaledHeight; scaledWidth = options.outWidth * targetDensity / inDensity; scaledHeight = options.outHeight * targetDensity / inDensity; if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "getResizedImageData: retry scaling using " + "Bitmap.createScaledBitmap: w=" + scaledWidth + ", h=" + scaledHeight); } if (square) { int w = b.getWidth(); int h = b.getHeight(); int dim = Math.min(w, h); b = Bitmap.createBitmap(b, (w - dim) / 2, (h - dim) / 2, dim, dim); scaledWidth = dim; scaledHeight = dim; } Bitmap b2 = Bitmap.createScaledBitmap(b, scaledWidth, scaledHeight, false); b.recycle(); b = b2; if (b == null) { return null; } } Matrix matrix = new Matrix(); if (mRotation != 0f) { matrix.preRotate(mRotation); } Bitmap old = b; b = Bitmap.createBitmap(old, 0, 0, old.getWidth(), old.getHeight(), matrix, true); // Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY. // In case that the image byte size is still too large reduce the quality in // proportion to the desired byte size. Should the quality fall below // MINIMUM_IMAGE_COMPRESSION_QUALITY skip a compression attempt and we will enter // the next round with a smaller image to start with. os = new ByteArrayOutputStream(); b.compress(CompressFormat.JPEG, quality, os); int jpgFileSize = os.size(); if (jpgFileSize > byteLimit) { int reducedQuality = quality * byteLimit / jpgFileSize; //always try to squish it before computing the new size if (reducedQuality < MINIMUM_IMAGE_COMPRESSION_QUALITY) { reducedQuality = MINIMUM_IMAGE_COMPRESSION_QUALITY; } quality = reducedQuality; if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality); } os = new ByteArrayOutputStream(); b.compress(CompressFormat.JPEG, quality, os); } b.recycle(); // done with the bitmap, release the memory } catch (java.lang.OutOfMemoryError e) { Log.w(TAG, "getResizedImageData - image too big (OutOfMemoryError), will try " + " with smaller scale factor, cur scale factor", e); lowMemoryReduce *= 2; // fall through and keep trying with a smaller scale factor. } if (true || Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "attempt=" + attempts + " size=" + (os == null ? 0 : os.size()) + " width=" + options.outWidth + " height=" + options.outHeight + " Ratio=" + targetDensity + "/" + inDensity + " quality=" + quality); } //move halfway to the target targetDensity = (os == null) ? (int) (targetDensity * .8) : (targetDensity * byteLimit / os.size() + targetDensity) / 2; attempts++; } while ((os == null || os.size() > byteLimit) && attempts < NUMBER_OF_RESIZE_ATTEMPTS); return os == null ? null : os.toByteArray(); } catch (Throwable t) { Log.e(TAG, t.getMessage(), t); return null; } finally { if (input != null) { try { input.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } } }
From source file:fr.neamar.notiflow.GcmIntentService.java
private void sendNotification(String flow, String msg, Bundle extras) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); Boolean notifyOwnMessages = prefs.getBoolean("prefNotifyOwnMessages", false); Boolean isOwnMessage = extras.getString("own", "false").equals("true"); String notifyType = prefs.getString("prefNotifyType", "all"); // all | mentions | private Boolean isMentioned = extras.getString("mentioned", "false").equals("true"); Boolean isPrivate = extras.getString("private", "false").equals("true"); Log.d(TAG, "New message, type " + notifyType + ", mentioned: " + isMentioned + ", private: " + isPrivate); if (isOwnMessage && !notifyOwnMessages) { Log.i(TAG, "Canceling notification (user sent): " + extras.toString()); mNotificationManager.cancel(extras.getString("flow"), 0); NotificationHelper.cleanNotifications(getApplicationContext(), extras.getString("flow")); return;/* w ww . j a v a 2 s . c om*/ } else if (notifyType.equals("mentions") && !isMentioned && !isPrivate) { Log.i(TAG, "Skipping message (not mentioned): " + extras.toString()); return; } else if (notifyType.equals("private") && !isPrivate) { Log.i(TAG, "Skipping message (not private): " + extras.toString()); return; } Date lastNotification = NotificationHelper.getLastNotificationDate(getApplicationContext(), flow); NotificationHelper.addNotification(getApplicationContext(), flow, msg); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender(); Boolean silentMode = prefs.getBoolean("prefNotifySilent", false); if (!silentMode) { Date now = new Date(); Long timeSinceLastNotification = now.getTime() - lastNotification.getTime(); Integer frequency = Integer.parseInt(prefs.getString("prefNotifyVibrationFrequency", "15")) * 1000; Boolean notifyWhenActive = prefs.getBoolean("prefNotifyWhenActive", false); Boolean isActive = extras.getString("active", "false").equals("true"); if (timeSinceLastNotification < frequency) { Log.i(TAG, "Skipping vibration -- cooldown in effect"); } else if (isActive && !notifyWhenActive) { Log.i(TAG, "Skipping vibration -- user already active"); } else { mBuilder.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS); } } ArrayList<String> prevMessages = NotificationHelper.getNotifications(getApplicationContext(), flow); Integer pendingCount = prevMessages.size(); if (pendingCount == 1) { // Only one notification : display using BigTextStyle for multiline. NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle() .bigText(Html.fromHtml(msg)); mBuilder.setStyle(style); } else { // More than one notification: use inbox style, displaying up to 5 messages NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(); for (int i = 0; i < Math.min(pendingCount, 5); i++) { style.addLine(Html.fromHtml(prevMessages.get(i))); } mBuilder.setStyle(style).setContentInfo(Integer.toString(pendingCount)).setNumber(pendingCount); NotificationCompat.BigTextStyle pageStyle = new NotificationCompat.BigTextStyle(); StringBuilder pageText = new StringBuilder(); // And then add a second page for Wearables, displaying the whole pending conversation for (int i = pendingCount - 1; i >= 0; i--) { if (i < pendingCount - 1) { pageText.append("<br /><br />"); } pageText.append(prevMessages.get(i)); } pageStyle.bigText(Html.fromHtml(pageText.toString())); Notification secondPage = new NotificationCompat.Builder(this).setStyle(pageStyle) .extend(new NotificationCompat.WearableExtender().setStartScrollBottom(true)).build(); wearableExtender.addPage(secondPage); } // Set large icon, which gets used for wearable background as well String avatar = extras.getString("avatar", ""); if (!avatar.equals("")) { String sizeExpr = "(/\\d+/?)$"; Boolean isCloudFront = avatar.contains("cloudfront"); Boolean hasSize = avatar.matches(".*" + sizeExpr); if (isCloudFront) { if (!hasSize) { avatar += "/400"; } else { avatar.replaceFirst(sizeExpr, "/400"); } } ImageLoader imageLoader = ImageLoader.getInstance(); Bitmap image = imageLoader.loadImageSync(avatar); // scale for notification tray int height = (int) getResources().getDimension(android.R.dimen.notification_large_icon_height); int width = (int) getResources().getDimension(android.R.dimen.notification_large_icon_width); Bitmap scaledImage = Bitmap.createScaledBitmap(image, width, height, false); mBuilder.setLargeIcon(scaledImage); wearableExtender.setBackground(image); } // Increase priority only for mentions and 1-1 conversations if (isMentioned || isPrivate) { mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH); } // Retrieve color // Default to 0x7BD3FB int color = Integer.parseInt(extras.getString("color", "8115195")); Notification notification = mBuilder.setSmallIcon(R.drawable.notification).setColor(color) .setContentTitle(flow).setContentText(Html.fromHtml(msg)).setAutoCancel(true) .setContentIntent(createClickedIntent(flow, extras)).setDeleteIntent(createDismissedIntent(flow)) .setTicker(Html.fromHtml(msg)).setCategory(Notification.CATEGORY_SOCIAL).extend(wearableExtender) .build(); mNotificationManager.notify(flow, 0, notification); Log.i(TAG, "Displaying message: " + extras.toString()); }
From source file:com.android.contacts.editor.EditorUiUtils.java
/** Returns compressed bitmap bytes from the given Uri, scaled to the thumbnail dimensions. */ public static byte[] getCompressedThumbnailBitmapBytes(Context context, Uri uri) throws FileNotFoundException { final Bitmap bitmap = ContactPhotoUtils.getBitmapFromUri(context, uri); final int size = ContactsUtils.getThumbnailSize(context); final Bitmap bitmapScaled = Bitmap.createScaledBitmap(bitmap, size, size, /* filter =*/ false); return ContactPhotoUtils.compressBitmap(bitmapScaled); }
From source file:cx.ring.model.Conference.java
public void showCallNotification(Context ctx) { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(ctx); notificationManager.cancel(notificationId); if (getParticipants().isEmpty()) return;// w w w . j av a 2 s .c o m SipCall call = getParticipants().get(0); CallContact contact = call.getContact(); final Uri call_uri = Uri.withAppendedPath(SipCall.CONTENT_URI, call.getCallId()); PendingIntent goto_intent = PendingIntent.getActivity(ctx, new Random().nextInt(), getViewIntent(ctx), PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder noti = new NotificationCompat.Builder(ctx); if (isOnGoing()) { noti.setContentTitle(ctx.getString(R.string.notif_current_call_title, contact.getDisplayName())) .setContentText(ctx.getText(R.string.notif_current_call)).setContentIntent(goto_intent) .addAction(R.drawable.ic_call_end_white_24dp, ctx.getText(R.string.action_call_hangup), PendingIntent.getService( ctx, new Random().nextInt(), new Intent(LocalService.ACTION_CALL_END) .setClass(ctx, LocalService.class).setData(call_uri), PendingIntent.FLAG_ONE_SHOT)); } else if (isRinging()) { if (isIncoming()) { noti.setContentTitle(ctx.getString(R.string.notif_incoming_call_title, contact.getDisplayName())) .setPriority(NotificationCompat.PRIORITY_MAX) .setContentText(ctx.getText(R.string.notif_incoming_call)).setContentIntent(goto_intent) .setFullScreenIntent(goto_intent, true) .addAction(R.drawable.ic_action_accept, ctx.getText(R.string.action_call_accept), PendingIntent.getService(ctx, new Random().nextInt(), new Intent(LocalService.ACTION_CALL_ACCEPT) .setClass(ctx, LocalService.class).setData(call_uri), PendingIntent.FLAG_ONE_SHOT)) .addAction(R.drawable.ic_call_end_white_24dp, ctx.getText(R.string.action_call_decline), PendingIntent.getService(ctx, new Random().nextInt(), new Intent(LocalService.ACTION_CALL_REFUSE) .setClass(ctx, LocalService.class).setData(call_uri), PendingIntent.FLAG_ONE_SHOT)); } else { noti.setContentTitle(ctx.getString(R.string.notif_outgoing_call_title, contact.getDisplayName())) .setContentText(ctx.getText(R.string.notif_outgoing_call)).setContentIntent(goto_intent) .addAction(R.drawable.ic_call_end_white_24dp, ctx.getText(R.string.action_call_hangup), PendingIntent.getService( ctx, new Random().nextInt(), new Intent(LocalService.ACTION_CALL_END) .setClass(ctx, LocalService.class).setData(call_uri), PendingIntent.FLAG_ONE_SHOT)); } } else { notificationManager.cancel(notificationId); return; } noti.setOngoing(true).setCategory(NotificationCompat.CATEGORY_CALL).setSmallIcon(R.drawable.ic_launcher); if (contact.getPhoto() != null) { Resources res = ctx.getResources(); int height = (int) res.getDimension(android.R.dimen.notification_large_icon_height); int width = (int) res.getDimension(android.R.dimen.notification_large_icon_width); noti.setLargeIcon(Bitmap.createScaledBitmap(contact.getPhoto(), width, height, false)); } notificationManager.notify(notificationId, noti.build()); }
From source file:co.mwater.foregroundcameraplugin.ForegroundCameraLauncher.java
/** * Scales the bitmap according to the requested size. * /*from ww w . j av a 2s. c om*/ * @param bitmap * The bitmap to scale. * @return Bitmap A new Bitmap object of the same bitmap after scaling. */ public Bitmap scaleBitmap(Bitmap bitmap) { int newWidth = this.targetWidth; int newHeight = this.targetHeight; int origWidth = bitmap.getWidth(); int origHeight = bitmap.getHeight(); // If no new width or height were specified return the original bitmap if (newWidth <= 0 && newHeight <= 0) { return bitmap; } // Only the width was specified else if (newWidth > 0 && newHeight <= 0) { newHeight = (newWidth * origHeight) / origWidth; } // only the height was specified else if (newWidth <= 0 && newHeight > 0) { newWidth = (newHeight * origWidth) / origHeight; } // If the user specified both a positive width and height // (potentially different aspect ratio) then the width or height is // scaled so that the image fits while maintaining aspect ratio. // Alternatively, the specified width and height could have been // kept and Bitmap.SCALE_TO_FIT specified when scaling, but this // would result in whitespace in the new image. else { double newRatio = newWidth / (double) newHeight; double origRatio = origWidth / (double) origHeight; if (origRatio > newRatio) { newHeight = (newWidth * origHeight) / origWidth; } else if (origRatio < newRatio) { newWidth = (newHeight * origWidth) / origHeight; } } return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true); }
From source file:com.github.topbottomsnackbar.TBSnackbar.java
private Drawable fitDrawable(Drawable drawable, int sizePx) { if (drawable.getIntrinsicWidth() != sizePx || drawable.getIntrinsicHeight() != sizePx) { if (drawable instanceof BitmapDrawable) { drawable = new BitmapDrawable(mContext.getResources(), Bitmap.createScaledBitmap(getBitmap(drawable), sizePx, sizePx, true)); }/* w ww . j a v a 2 s. co m*/ } drawable.setBounds(0, 0, sizePx, sizePx); return drawable; }
From source file:com.atinternet.tracker.Tool.java
/** * Resize an image//w ww. ja v a 2 s. c o m * * @param imageID int * @param context Context * @param width int * @param height int * @return Drawable */ static Drawable getResizedImage(int imageID, Context context, int width, int height) { Bitmap b = BitmapFactory.decodeResource(context.getResources(), imageID); Bitmap bitmapResized = Bitmap.createScaledBitmap(b, width, height, false); return new BitmapDrawable(context.getResources(), bitmapResized); }
From source file:net.ustyugov.jtalk.activity.vcard.SetVcardActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == IMAGE && data != null) { Uri uri = Uri.parse(data.getDataString()); if (uri != null) { try { FileInputStream fileInput = getContentResolver().openAssetFileDescriptor(uri, "r") .createInputStream(); bytes = new byte[fileInput.available()]; fileInput.read(bytes); Bitmap bm = Bitmap.createScaledBitmap(BitmapFactory.decodeFileDescriptor(fileInput.getFD()), 240, 240, true); av.setImageBitmap(bm); fileInput.close();/*from w ww . jav a 2 s .c o m*/ } catch (FileNotFoundException e) { } catch (IOException e) { } } } } }