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:com.gfan.sbbs.utils.images.ImageManager.java
/** * Bitmap//w w w . j a v a 2 s .c o m * * @param bitmap * @param maxWidth * @param maxHeight * @param quality * 1~100 * @return */ public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) { Log.i(TAG, "resizing a bitmap"); if (null == bitmap) { return null; } int originWidth = bitmap.getWidth(); int originHeight = bitmap.getHeight(); // no need to resize if (originWidth < maxWidth && originHeight < maxHeight) { return bitmap; } int newWidth = originWidth; int newHeight = originHeight; Bitmap newBitmap = null; // , if (originWidth > maxWidth) { newWidth = maxWidth; double i = originWidth * 1.0 / maxWidth; newHeight = (int) Math.floor(originHeight / i); newBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true); } // , if (newHeight > maxHeight) { newHeight = maxHeight; int half_diff = (int) ((originHeight - maxHeight) / 2.0); newBitmap = Bitmap.createBitmap(bitmap, 0, half_diff, newWidth, newHeight); } bitmap.recycle(); Log.d(TAG, newWidth + " width"); Log.d(TAG, newHeight + " height"); return newBitmap; }
From source file:ch.uzh.supersede.feedbacklibrary.utils.Utils.java
/** * This method scales the bitmap according to a maximum width and height keeping the aspect ratio. * * @param bitmap the original bitmap//w w w. j a v a2 s .c o m * @param maxWidth the maximum width to scale * @param maxHeight the minimum width to scale * @return the scaled bitmap */ public static Bitmap scaleBitmap(Bitmap bitmap, int maxWidth, int maxHeight) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); if (width > height) { // Landscape float ratio = (float) width / maxWidth; width = maxWidth; height = (int) (height / ratio); } else if (height > width) { // Portrait float ratio = (float) height / maxHeight; height = maxHeight; width = (int) (width / ratio); } else { // Square height = maxHeight; width = maxWidth; } return Bitmap.createScaledBitmap(bitmap, width, height, true); }
From source file:de.uulm.graphicalpasswords.openmiba.MIBACreatePasswordActivity.java
private void setViews() { tblLayout = (TableLayout) findViewById(R.id.tableLayout); btnBack = (Button) findViewById(R.id.miba_btnBack); btnBack.setOnClickListener(new View.OnClickListener() { @Override//ww w. j a v a 2s .co m public void onClick(View v) { back(); } }); btnDone = (Button) findViewById(R.id.miba_btnCreateMasterKey); tvRound = (TextView) this.findViewById(R.id.tvRound); tvRound.setText(getString(R.string.label_round) + " 1"); linlGrid = new LinearLayout[2][4]; linlGrid[0][0] = (LinearLayout) this.findViewById(R.id.square1); linlGrid[1][0] = (LinearLayout) this.findViewById(R.id.square2); linlGrid[0][1] = (LinearLayout) this.findViewById(R.id.square3); linlGrid[1][1] = (LinearLayout) this.findViewById(R.id.square4); linlGrid[0][2] = (LinearLayout) this.findViewById(R.id.square5); linlGrid[1][2] = (LinearLayout) this.findViewById(R.id.square6); linlGrid[0][3] = (LinearLayout) this.findViewById(R.id.square7); linlGrid[1][3] = (LinearLayout) this.findViewById(R.id.square8); for (int y = 0; y < 4; y++) { for (int x = 0; x < 2; x++) { linlGrid[x][y].setBackgroundColor(colors_off[x][y]); } } // get width and height from mainpanel // can not use display width/height because of notification bar ViewTreeObserver vto = tblLayout.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // get values of portrait mode Display display = getWindowManager().getDefaultDisplay(); if (display.getRotation() == Surface.ROTATION_0) { width = tblLayout.getWidth(); height = tblLayout.getHeight(); } else { height = tblLayout.getWidth(); width = tblLayout.getHeight(); } Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ccp000); bmp = Bitmap.createScaledBitmap(bmp, width, height, true); Drawable d = new BitmapDrawable(getResources(), bmp); tblLayout.setBackgroundDrawable(d); touchlistener = new TouchListener(linlGrid, width, height, handler); tblLayout.setOnTouchListener(touchlistener); // remove listener again otherwise it gets called twice tblLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this); } }); btnDone.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DialogFragment dialog = new RememberPasswordDialogFragment(); dialog.show(getFragmentManager(), "remember"); } }); btnDone.setVisibility(View.VISIBLE); }
From source file:com.projectattitude.projectattitude.Activities.ViewProfileActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri uri = data.getData();/* ww w .j a v a2 s . com*/ try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); // Log.d(TAG, String.valueOf(bitmap)); Log.d("PhotoBytes1", bitmap.getByteCount() + ""); Log.d("PhotoHeight1", bitmap.getHeight() + ""); Log.d("PhotoHeight1", bitmap.getWidth() + ""); //if greater then byte threshold, compress if (bitmap.getByteCount() > 65536) { while (bitmap.getByteCount() > 65536) { //Keep compressing photo until photo is small enough bitmap = Bitmap.createScaledBitmap(bitmap, (bitmap.getWidth() / 2), (bitmap.getHeight() / 2), false); Log.d("imageCompressed", bitmap.getByteCount() + ""); } } ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); s = Base64.encodeToString(byteArray, Base64.DEFAULT); image.setImageBitmap(bitmap); user.setPhoto(s); //TODO Update the database } catch (IOException e) { e.printStackTrace(); } //TODO: Update user with profile picture userController.getActiveUser().setPhoto(s); ElasticSearchUserController.UpdateUserPictureTask updateUserPictureTask = new ElasticSearchUserController.UpdateUserPictureTask(); updateUserPictureTask.execute(UserController.getInstance().getActiveUser()); } }
From source file:ca.ualberta.app.activity.CreateAnswerActivity.java
/** * scale the image to fixed width and height * // w ww . j a v a 2 s . c om * @param width * the fixed width * @param height * the fixed height * @param createThumb * single to create a thumb nail of the image */ private void scaleImage(int width, int height, boolean createThumb) { // Scale the pic if it is too large: double scaleFactor = 1; if (image.getWidth() > width) { scaleFactor = image.getWidth() / width; } else if (image.getHeight() > height && image.getHeight() > image.getWidth()) { scaleFactor = image.getHeight() / height; } int newWidth = (int) Math.round(image.getWidth() / scaleFactor); int newHeight = (int) Math.round(image.getHeight() / scaleFactor); if (createThumb) imageThumb = Bitmap.createScaledBitmap(image, newWidth, newHeight, false); else image = Bitmap.createScaledBitmap(image, newWidth, newHeight, false); }
From source file:me.myatminsoe.myansms.SmsReceiver.java
/** * Update new message {@link Notification}. * * @param context {@link Context}//from ww w . j ava2 s . co m * @param text text of the last assumed unread message * @return number of unread messages */ static int updateNewMessageNotification(final Context context, final String text) { final NotificationManager mNotificationMgr = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final boolean enableNotifications = prefs.getBoolean(PreferencesActivity.PREFS_NOTIFICATION_ENABLE, true); final boolean privateNotification = prefs.getBoolean(PreferencesActivity.PREFS_NOTIFICATION_PRIVACY, false); final boolean showPhoto = !privateNotification && prefs.getBoolean(PreferencesActivity.PREFS_CONTACT_PHOTO, true); if (!enableNotifications) { mNotificationMgr.cancelAll(); Log.d(TAG, "no notification needed!"); } final int[] status = getUnread(context.getContentResolver(), text); final int l = status[ID_COUNT]; final int tid = status[ID_TID]; // FIXME l is always -1.. if (l < 0) { return l; } if (enableNotifications && (text != null || l == 0)) { mNotificationMgr.cancel(NOTIFICATION_ID_NEW); } Uri uri; PendingIntent pIntent; if (l == 0) { final Intent i = new Intent(context, ConversationListActivity.class); // add pending intent i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); } else { final NotificationCompat.Builder nb = new NotificationCompat.Builder(context); boolean showNotification = true; Intent i; if (tid >= 0) { uri = Uri.parse(MessageListActivity.URI + tid); i = new Intent(Intent.ACTION_VIEW, uri, context, MessageListActivity.class); pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); if (enableNotifications) { final Conversation conv = Conversation.getConversation(context, tid, true); if (conv != null) { String a; if (privateNotification) { if (l == 1) { a = context.getString(R.string.new_message_); } else { a = context.getString(R.string.new_messages_); } } else { a = conv.getContact().getDisplayName(); } showNotification = true; nb.setSmallIcon(PreferencesActivity.getNotificationIcon(context)); nb.setTicker(a); nb.setWhen(lastUnreadDate); if (l == 1) { String body; if (privateNotification) { body = context.getString(R.string.new_message); } else { body = lastUnreadBody; } if (body == null) { body = context.getString(R.string.mms_conversation); } nb.setContentTitle(a); nb.setContentText(body); nb.setContentIntent(pIntent); // add long text nb.setStyle(new NotificationCompat.BigTextStyle().bigText(body)); // add actions Intent nextIntent = new Intent(NotificationBroadcastReceiver.ACTION_MARK_READ); nextIntent.putExtra(NotificationBroadcastReceiver.EXTRA_MURI, uri.toString()); PendingIntent nextPendingIntent = PendingIntent.getBroadcast(context, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT); nb.addAction(R.drawable.ic_done_24dp, context.getString(R.string.mark_read_), nextPendingIntent); nb.addAction(R.drawable.ic_reply_24dp, context.getString(R.string.reply), pIntent); } else { nb.setContentTitle(a); nb.setContentText(context.getString(R.string.new_messages, l)); nb.setContentIntent(pIntent); } if (showPhoto // just for the speeeeed && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { try { conv.getContact().update(context, false, true); } catch (NullPointerException e) { Log.e(TAG, "updating contact failed", e); } Drawable d = conv.getContact().getAvatar(context, null); if (d instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable) d).getBitmap(); // 24x24 dp according to android iconography -> // http://developer.android.com/design/style/iconography.html#notification int px = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 64, context.getResources().getDisplayMetrics())); nb.setLargeIcon(Bitmap.createScaledBitmap(bitmap, px, px, false)); } } } } } else { uri = Uri.parse(MessageListActivity.URI); i = new Intent(Intent.ACTION_VIEW, uri, context, ConversationListActivity.class); pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); if (enableNotifications) { showNotification = true; nb.setSmallIcon(PreferencesActivity.getNotificationIcon(context)); nb.setTicker(context.getString(R.string.new_messages_)); nb.setWhen(lastUnreadDate); nb.setContentTitle(context.getString(R.string.new_messages_)); nb.setContentText(context.getString(R.string.new_messages, l)); nb.setContentIntent(pIntent); nb.setNumber(l); } } // add pending intent i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); if (enableNotifications && showNotification) { int[] ledFlash = PreferencesActivity.getLEDflash(context); nb.setLights(PreferencesActivity.getLEDcolor(context), ledFlash[0], ledFlash[1]); final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); if (text != null) { final boolean vibrate = p.getBoolean(PreferencesActivity.PREFS_VIBRATE, false); final String s = p.getString(PreferencesActivity.PREFS_SOUND, null); Uri sound; if (s == null || s.length() <= 0) { sound = null; } else { sound = Uri.parse(s); } if (vibrate) { final long[] pattern = PreferencesActivity.getVibratorPattern(context); if (pattern.length == 1 && pattern[0] == 0) { nb.setDefaults(Notification.DEFAULT_VIBRATE); } else { nb.setVibrate(pattern); } } nb.setSound(sound); } } mNotificationMgr.cancel(NOTIFICATION_ID_NEW); if (enableNotifications && showNotification) { try { mNotificationMgr.notify(NOTIFICATION_ID_NEW, nb.getNotification()); } catch (IllegalArgumentException e) { } } } //noinspection ConstantConditions return l; }
From source file:net.ben.subsonic.androidapp.service.RESTMusicService.java
@Override public Bitmap getCoverArt(Context context, MusicDirectory.Entry entry, int size, boolean saveToFile, ProgressListener progressListener) throws Exception { // Synchronize on the entry so that we don't download concurrently for the same song. synchronized (entry) { // Use cached file, if existing. File albumArtFile = FileUtil.getAlbumArtFile(context, entry); if (albumArtFile.exists()) { InputStream in = new FileInputStream(albumArtFile); try { byte[] bytes = Util.toByteArray(in); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); return Bitmap.createScaledBitmap(bitmap, size, size, true); } finally { Util.close(in);/*from www . j a v a 2s .c o m*/ } } String url = Util.getRestUrl(context, "getCoverArt"); InputStream in = null; try { List<String> parameterNames = Arrays.asList("id", "size"); List<Object> parameterValues = Arrays.<Object>asList(entry.getCoverArt(), size); HttpEntity entity = getEntityForURL(context, url, null, parameterNames, parameterValues, progressListener); in = entity.getContent(); // If content type is XML, an error occured. Get it. String contentType = Util.getContentType(entity); if (contentType != null && contentType.startsWith("text/xml")) { new ErrorParser(context).parse(new InputStreamReader(in, Constants.UTF_8)); return null; // Never reached. } byte[] bytes = Util.toByteArray(in); if (saveToFile) { OutputStream out = null; try { out = new FileOutputStream(albumArtFile); out.write(bytes); } finally { Util.close(out); } } return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } finally { Util.close(in); } } }
From source file:org.catrobat.paintroid.test.integration.BaseIntegrationTestClass.java
protected void scaleDownTestBitmap(float scaleFactor) { mCurrentDrawingSurfaceBitmap = Bitmap.createScaledBitmap(mCurrentDrawingSurfaceBitmap, (int) (mCurrentDrawingSurfaceBitmap.getWidth() * scaleFactor), (int) (mCurrentDrawingSurfaceBitmap.getHeight() * scaleFactor), false); PaintroidApplication.drawingSurface.setBitmap(mCurrentDrawingSurfaceBitmap); mSolo.sleep(200);//from ww w . j a va 2 s . c o m PaintroidApplication.perspective.resetScaleAndTranslation(); }
From source file:com.almalence.googsharing.Thumbnail.java
private static Bitmap createVideoThumbnail(String filePath, FileDescriptor fd, int targetWidth) { Bitmap bitmap = null;/*from w w w. jav a 2 s. c om*/ MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { if (filePath != null) { retriever.setDataSource(filePath); } else { retriever.setDataSource(fd); } bitmap = retriever.getFrameAtTime(-1); } catch (IllegalArgumentException ex) { // Assume this is a corrupt video file } catch (RuntimeException ex) { // Assume this is a corrupt video file. } finally { try { retriever.release(); } catch (RuntimeException ex) { // Ignore failures while cleaning up. } } if (bitmap == null) return null; // Scale down the bitmap if it is bigger than we need. int width = bitmap.getWidth(); int height = bitmap.getHeight(); if (width > targetWidth) { float scale = (float) targetWidth / width; int w = Math.round(scale * width); int h = Math.round(scale * height); bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true); } return bitmap; }
From source file:com.flyingcrop.ScreenCaptureFragment.java
public Bitmap resize(Bitmap bitmap) { Bitmap resizedBitmap = null;/*from w w w . ja v a 2s . c om*/ int originalWidth = bitmap.getWidth(); int originalHeight = bitmap.getHeight(); int newWidth = -1; int newHeight = -1; float multFactor = -1.0F; if (Math.abs(y_inicial - y_final) < Math.abs(x_inicial - x_final)) { newHeight = (int) (Math.abs(y_inicial - y_final) * 0.4); newWidth = newHeight; } else { newHeight = (int) (Math.abs(x_inicial - x_final) * 0.4); newWidth = newHeight; } resizedBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false); return resizedBitmap; }