List of usage examples for android.graphics Bitmap recycle
public void recycle()
From source file:Main.java
public static Bitmap createScaledRotatedBitmapFromFile(String filePath, int reqWidth, int reqHeight, int orientation) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;/*from w ww .j av a2 s . c o m*/ BitmapFactory.decodeFile(filePath, options); Bitmap bitmap; int rotationAngle = 0, outHeight = 0, outWidth = 0; if (reqWidth >= reqHeight) { if (options.outWidth >= options.outHeight) { if (orientation != 1) { rotationAngle = 180; } else { } bitmap = decodeSampledBitmapFromFile(filePath, reqWidth, reqHeight); } else { bitmap = decodeSampledBitmapFromFile(filePath, reqHeight, reqWidth); } outHeight = bitmap.getWidth(); outWidth = bitmap.getHeight(); } else { if (options.outWidth > options.outHeight) { if (orientation != 1) { rotationAngle = 90; } else { rotationAngle = 270; } bitmap = decodeSampledBitmapFromFile(filePath, reqHeight, reqWidth); } else { bitmap = decodeSampledBitmapFromFile(filePath, reqWidth, reqHeight); } outHeight = bitmap.getWidth(); outWidth = bitmap.getHeight(); } if (rotationAngle == 0) { return bitmap; } Matrix matrix = new Matrix(); matrix.setRotate(rotationAngle, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2); Bitmap rotateBitmap = Bitmap.createBitmap(bitmap, 0, 0, outHeight, outWidth, matrix, true); if (bitmap != rotateBitmap) { bitmap.recycle(); } return rotateBitmap; }
From source file:Main.java
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int color, int cornerDips, int borderDips, Context context, boolean recycleOrig) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int borderSizePx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) borderDips, context.getResources().getDisplayMetrics()); final int cornerSizePx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) cornerDips, context.getResources().getDisplayMetrics()); final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); // prepare canvas for transfer paint.setAntiAlias(true);/*w ww .j a va2s . c o m*/ paint.setColor(0xFFFFFFFF); paint.setStyle(Paint.Style.FILL); canvas.drawARGB(0, 0, 0, 0); canvas.drawRoundRect(rectF, cornerSizePx, cornerSizePx, paint); // draw bitmap paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); // draw border paint.setColor(color); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth((float) borderSizePx); canvas.drawRoundRect(rectF, cornerSizePx, cornerSizePx, paint); if (recycleOrig && bitmap != null && !bitmap.isRecycled()) bitmap.recycle(); return output; }
From source file:com.concentricsky.android.khanacademy.app.TopicListActivity.java
@Override public void onStop() { Log.d(LOG_TAG, "onStop"); stopped = true;//from w ww . j a va2 s. c o m if (gridView != null) { gridView.setOnItemClickListener(null); TopicGridAdapter adapter = (TopicGridAdapter) gridView.getAdapter(); if (adapter != null) { adapter.changeCursor(null); adapter.renderer.stop(); adapter.renderer.clearCache(); } gridView.setAdapter(null); gridView = null; } if (headerView != null) { final ImageView thumb = (ImageView) headerView.findViewById(R.id.header_video_list_thumbnail); // thumb.setImageResource(0); Drawable d = thumb.getDrawable(); if (d instanceof BitmapDrawable) { Bitmap bmp = ((BitmapDrawable) d).getBitmap(); if (bmp != null) { bmp.recycle(); } } } LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); receiver = null; super.onStop(); }
From source file:com.apptentive.android.sdk.model.FileMessage.java
/** * This method stores an image, and compresses it in the process so it doesn't fill up the disk. Therefore, do not use * it to store an exact copy of the file in question. *//* ww w . ja v a 2 s . c o m*/ public boolean internalCreateStoredImage(Context context, String uriString) { Uri uri = Uri.parse(uriString); ContentResolver resolver = context.getContentResolver(); String mimeType = resolver.getType(uri); MimeTypeMap mime = MimeTypeMap.getSingleton(); String extension = mime.getExtensionFromMimeType(mimeType); setFileName(uri.getLastPathSegment() + "." + extension); setMimeType(mimeType); // Create a file to save locally. String localFileName = getStoredFileId(); File localFile = new File(localFileName); // Copy the file contents over. InputStream is = null; CountingOutputStream cos = null; try { is = new BufferedInputStream(context.getContentResolver().openInputStream(uri)); cos = new CountingOutputStream( new BufferedOutputStream(context.openFileOutput(localFile.getPath(), Context.MODE_PRIVATE))); System.gc(); Bitmap smaller = ImageUtil.createScaledBitmapFromStream(is, MAX_STORED_IMAGE_EDGE, MAX_STORED_IMAGE_EDGE, null); // TODO: Is JPEG what we want here? smaller.compress(Bitmap.CompressFormat.JPEG, 95, cos); cos.flush(); Log.d("Bitmap saved, size = " + (cos.getBytesWritten() / 1024) + "k"); smaller.recycle(); System.gc(); } catch (FileNotFoundException e) { Log.e("File not found while storing image.", e); return false; } catch (Exception e) { Log.a("Error storing image.", e); return false; } finally { Util.ensureClosed(is); Util.ensureClosed(cos); } // Create a StoredFile database entry for this locally saved file. StoredFile storedFile = new StoredFile(); storedFile.setId(getStoredFileId()); storedFile.setOriginalUri(uri.toString()); storedFile.setLocalFilePath(localFile.getPath()); storedFile.setMimeType("image/jpeg"); FileStore db = ApptentiveDatabase.getInstance(context); return db.putStoredFile(storedFile); }
From source file:Main.java
/** * // w w w . j a v a 2 s . com * @param filePath * @param targetWidth * @param targetHeight * @param recycle * @return */ public static Bitmap resizeAndCropCenter(Bitmap bitmap, int targetWidth, int targetHeight, boolean recycle) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); int scaleWidth = w / targetWidth; int scaleHeight = h / targetHeight; int scale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight; if (scale < 1) { scale = 1; } //get scalebitmap float fScaleWidth = targetWidth / ((float) w); float fScaleHeight = targetHeight / ((float) h); float fScale = fScaleWidth > fScaleHeight ? fScaleWidth : fScaleHeight; if (fScale > 1) fScale = 1; Matrix matrix = new Matrix(); matrix.postScale(fScale, fScale); Bitmap scaleBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true); //get targetBitmap int bitmapX = (scaleBitmap.getWidth() - targetWidth) / 2; bitmapX = bitmapX > 0 ? bitmapX : 0; int bitmapY = (scaleBitmap.getHeight() - targetHeight) / 2; bitmapY = bitmapY > 0 ? bitmapY : 0; targetWidth = targetWidth < (scaleBitmap.getWidth()) ? targetWidth : (scaleBitmap.getWidth()); targetHeight = targetHeight < (scaleBitmap.getHeight()) ? targetHeight : (scaleBitmap.getHeight()); Bitmap targetBitmap = Bitmap.createBitmap(scaleBitmap, bitmapX, bitmapY, targetWidth, targetHeight); // if (recycle) bitmap.recycle(); if (targetBitmap != bitmap && recycle) { bitmap.recycle(); } return targetBitmap; }
From source file:com.android.volley.toolbox.ImageRequest.java
/** * The real guts of parseNetworkResponse. Broken out for readability. *//*from w w w. j ava 2 s. co m*/ private Response<Bitmap> doParse(NetworkResponse response) { byte[] data = response.data; BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); Bitmap bitmap = null; if (mMaxWidth == 0 && mMaxHeight == 0) { decodeOptions.inPreferredConfig = mDecodeConfig; bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); } else { // If we have to resize this image, first get the natural bounds. decodeOptions.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); int actualWidth = decodeOptions.outWidth; int actualHeight = decodeOptions.outHeight; // Then compute the dimensions we would ideally like to decode to. int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight, actualWidth, actualHeight, mScaleType); int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth, actualHeight, actualWidth, mScaleType); // Decode to the nearest power of two scaling factor. decodeOptions.inJustDecodeBounds = false; // TODO(ficus): Do we need this or is it okay since API 8 doesn't support it? // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED; decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight); Bitmap tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); // If necessary, scale down to the maximal acceptable size. if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) { bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true); tempBitmap.recycle(); } else { bitmap = tempBitmap; } } if (bitmap == null) { return Response.error(new ParseError(response)); } else { return Response.success(bitmap, HttpHeaderParser.parseCacheHeaders(response)); } }
From source file:Main.java
/** * // w w w . j a v a 2s .c o m * @param filePath * @param targetWidth * @param targetHeight * @param recycle * @return */ public static Bitmap resizeAndCropCenter(Bitmap bitmap, int targetWidth, int targetHeight, boolean recycle) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); int scaleWidth = w / targetWidth; int scaleHeight = h / targetHeight; int scale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight; if (scale < 1) { scale = 1; } //get scalebitmap float fScaleWidth = targetWidth / ((float) w); float fScaleHeight = targetHeight / ((float) h); float fScale = fScaleWidth > fScaleHeight ? fScaleWidth : fScaleHeight; if (fScale > 1) fScale = 1; Matrix matrix = new Matrix(); matrix.postScale(fScale, fScale); Bitmap scaleBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true); //get targetBitmap int bitmapX = (scaleBitmap.getWidth() - targetWidth) / 2; bitmapX = bitmapX > 0 ? bitmapX : 0; int bitmapY = (scaleBitmap.getHeight() - targetHeight) / 2; bitmapY = bitmapY > 0 ? bitmapY : 0; targetWidth = targetWidth < (scaleBitmap.getWidth()) ? targetWidth : (scaleBitmap.getWidth()); targetHeight = targetHeight < (scaleBitmap.getHeight()) ? targetHeight : (scaleBitmap.getHeight()); if (bitmapX == 0 && bitmapY == 0 && targetWidth == w && targetHeight == h) { return bitmap; } Bitmap targetBitmap = Bitmap.createBitmap(scaleBitmap, bitmapX, bitmapY, targetWidth, targetHeight); if (recycle) bitmap.recycle(); return targetBitmap; }
From source file:com.irccloud.android.activity.PastebinEditorActivity.java
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= 21) { Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name), cloud, 0xFFF2F7FC));// w ww . java 2 s. c o m cloud.recycle(); } setContentView(R.layout.activity_pastebineditor); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { if (!getWindow().isFloating()) { getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } paste = (EditText) findViewById(R.id.paste); filename = (EditText) findViewById(R.id.filename); message = (EditText) findViewById(R.id.message); messages_count = (TextView) findViewById(R.id.messages_count); if (savedInstanceState != null && savedInstanceState.containsKey("message")) message.setText(savedInstanceState.getString("message")); if (savedInstanceState != null && savedInstanceState.containsKey("paste_id")) pasteID = savedInstanceState.getString("paste_id"); else if (getIntent() != null && getIntent().hasExtra("paste_id")) pasteID = getIntent().getStringExtra("paste_id"); if (savedInstanceState != null && savedInstanceState.containsKey("paste_contents")) pastecontents = savedInstanceState.getString("paste_contents"); else if (getIntent() != null && getIntent().hasExtra("paste_contents")) pastecontents = getIntent().getStringExtra("paste_contents"); paste.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { int count = 0; String lines[] = editable.toString().split("\n"); for (String line : lines) { count += Math.ceil(line.length() / 1080.0f); } messages_count.setText("Text will be sent as " + count + " message" + (count == 1 ? "" : "s")); } }); paste.setText(pastecontents); if (savedInstanceState != null && savedInstanceState.containsKey("filename")) filename.setText(savedInstanceState.getString("filename")); else if (getIntent() != null && getIntent().hasExtra("filename")) filename.setText(getIntent().getStringExtra("filename")); tabHost = (TabLayout) findViewById(android.R.id.tabhost); ViewCompat.setElevation(toolbar, ViewCompat.getElevation(tabHost)); if (pasteID != null) { tabHost.setVisibility(View.GONE); message.setVisibility(View.GONE); findViewById(R.id.message_heading).setVisibility(View.GONE); } else { tabHost.setTabGravity(TabLayout.GRAVITY_FILL); tabHost.setTabMode(TabLayout.MODE_FIXED); tabHost.addTab(tabHost.newTab().setText("Pastebin")); tabHost.addTab(tabHost.newTab().setText("Messages")); tabHost.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { current_tab = tab.getPosition(); if (current_tab == 0) { filename.setVisibility(View.VISIBLE); message.setVisibility(View.VISIBLE); messages_count.setVisibility(View.GONE); findViewById(R.id.filename_heading).setVisibility(View.VISIBLE); findViewById(R.id.message_heading).setVisibility(View.VISIBLE); } else { filename.setVisibility(View.GONE); message.setVisibility(View.GONE); messages_count.setVisibility(View.VISIBLE); findViewById(R.id.filename_heading).setVisibility(View.GONE); findViewById(R.id.message_heading).setVisibility(View.GONE); } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); if (savedInstanceState != null && savedInstanceState.containsKey("tab")) tabHost.getTabAt(savedInstanceState.getInt("tab")).select(); } NetworkConnection.getInstance().addHandler(this); if (pasteID != null && (pastecontents == null || pastecontents.length() == 0)) { new FetchPastebinTask().execute((Void) null); } if (pasteID != null) { setTitle(R.string.title_activity_pastebin_editor_edit); toolbar.setBackgroundResource(R.drawable.actionbar); } else { setTitle(R.string.title_activity_pastebin_editor); } supportInvalidateOptionsMenu(); result(RESULT_CANCELED); }
From source file:Main.java
private static int loadBitmapIntoOpenGL(Bitmap bitmap) { final int[] textureObjectIds = new int[1]; glGenTextures(1, textureObjectIds, 0); if (textureObjectIds[0] == 0) { if (IS_LOGGING_ON) { Log.w(TAG, "Could not generate a new OpenGL texture object."); }/* www . j a v a 2 s . co m*/ return 0; } if (bitmap == null) { if (IS_LOGGING_ON) { Log.w(TAG, "Bitmap could not be decoded."); } glDeleteTextures(1, textureObjectIds, 0); return 0; } // Bind to the texture in OpenGL glBindTexture(GL_TEXTURE_2D, textureObjectIds[0]); // Set filtering: a default must be set, or the texture will be // black. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Load the bitmap into the bound texture. texImage2D(GL_TEXTURE_2D, 0, bitmap, 0); // Note: Following code may cause an error to be reported in the // ADB log as follows: E/IMGSRV(20095): :0: HardwareMipGen: // Failed to generate texture mipmap levels (error=3) // No OpenGL error will be encountered (glGetError() will return // 0). If this happens, just squash the source image to be // square. It will look the same because of texture coordinates, // and mipmap generation will work. glGenerateMipmap(GL_TEXTURE_2D); // Recycle the bitmap, since its data has been loaded into // OpenGL. bitmap.recycle(); // Unbind from the texture. glBindTexture(GL_TEXTURE_2D, 0); return textureObjectIds[0]; }
From source file:Main.java
public static Bitmap toRoundBitmap(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float roundPx; float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom; if (width <= height) { roundPx = width / 2;//from w w w . j a v a 2 s .c o m top = 0; bottom = width; left = 0; right = width; height = width; dst_left = 0; dst_top = 0; dst_right = width; dst_bottom = width; } else { roundPx = height / 2; float clip = (width - height) / 2; left = clip; right = width - clip; top = 0; bottom = height; width = height; dst_left = 0; dst_top = 0; dst_right = height; dst_bottom = height; } Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom); final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom); final RectF rectF = new RectF(dst); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, src, dst, paint); bitmap.recycle(); return output; }