List of usage examples for android.graphics Bitmap recycle
public void recycle()
From source file:com.codegarden.nativenavigation.JuceActivity.java
public final int[] renderGlyph(char glyph, Paint paint, android.graphics.Matrix matrix, Rect bounds) { Path p = new Path(); paint.getTextPath(String.valueOf(glyph), 0, 1, 0.0f, 0.0f, p); RectF boundsF = new RectF(); p.computeBounds(boundsF, true);//from ww w . j a v a 2s .c o m matrix.mapRect(boundsF); boundsF.roundOut(bounds); bounds.left--; bounds.right++; final int w = bounds.width(); final int h = Math.max(1, bounds.height()); Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bm); matrix.postTranslate(-bounds.left, -bounds.top); c.setMatrix(matrix); c.drawPath(p, paint); final int sizeNeeded = w * h; if (cachedRenderArray.length < sizeNeeded) cachedRenderArray = new int[sizeNeeded]; bm.getPixels(cachedRenderArray, 0, w, 0, 0, w, h); bm.recycle(); return cachedRenderArray; }
From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java
/******************************* * /*from w w w. j a va2 s . co m*/ * createSmallAlbumArt * *******************************/ public void createSmallAlbumArt(String artistName, String albumName, boolean force) { /* * If small art already exists just return */ String smallArtFileName = ((RockPlayer) context).FILEX_SMALL_ALBUM_ART_PATH + validateFileName(artistName) + " - " + validateFileName(albumName) + FILEX_FILENAME_EXTENSION; Log.i("CREATE", smallArtFileName); File smallAlbumArtFile = new File(smallArtFileName); if (!force && smallAlbumArtFile.exists() && smallAlbumArtFile.length() > 0) { return; } /* * Get path for existing Album art */ String albumArtPath = getAlbumArtPath(artistName, albumName); /* * If album has art file create the small thumb from it * otherwise do it from the cdcover resource */ Bitmap smallBitmap = null; if (albumArtPath != null) { try { Log.i("SCALEBM", albumArtPath); // BitmapFactory.Options opts = new BitmapFactory.Options(); // opts.inJustDecodeBounds = true; // Bitmap bmTmp = BitmapFactory.decodeFile(albumArtPath, opts); // Log.i("DBG", ""+opts.outWidth+" "+opts.outHeight); // bmTmp.recycle(); FileInputStream albumArtPathStream = new FileInputStream(albumArtPath); Bitmap bm = BitmapFactory.decodeStream(albumArtPathStream); smallBitmap = Bitmap.createScaledBitmap(bm, 120, 120, false); albumArtPathStream.close(); bm.recycle(); } catch (Exception e) { // TODO: failed to get from library // show error //smallBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.albumart_mp_unknown); e.printStackTrace(); } catch (Error err) { err.printStackTrace(); } } else { //smallBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.albumart_mp_unknown); return; } try { if (smallAlbumArtFile != null) smallAlbumArtFile.createNewFile(); else Log.i("DBG", "smallAlbumArtFile is null ?????"); FileOutputStream smallAlbumArtFileStream = null; if (smallAlbumArtFile != null) smallAlbumArtFileStream = new FileOutputStream(smallAlbumArtFile); else Log.i("DBG", "smallAlbumArtFile is null ?????"); if (smallBitmap != null && smallAlbumArtFileStream != null) smallBitmap.compress(Bitmap.CompressFormat.JPEG, 90, smallAlbumArtFileStream); else Log.i("DBG", "smallBitmap or smallAlbumArtFileStream is null ?????"); if (smallAlbumArtFileStream != null) smallAlbumArtFileStream.close(); else Log.i("DBG", "smallAlbumArtFileStream is null ?????"); if (smallBitmap != null) smallBitmap.recycle(); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } }
From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java
/********************************* * //from w ww .ja v a 2 s. c om * albumHasArt * *********************************/ private String getAlbumArtPath(String artistName, String albumName) { String albumCoverPath = null; /* * 1. Check if we have downloaded it before */ // if(albumCoverPath == null){ String path = ((RockPlayer) context).FILEX_ALBUM_ART_PATH + validateFileName(artistName) + " - " + validateFileName(albumName) + FILEX_FILENAME_EXTENSION; File albumCoverFilePath = new File(path); if (albumCoverFilePath.exists() && albumCoverFilePath.length() > 0) { albumCoverPath = albumCoverFilePath.getAbsolutePath(); } // } /* * 2. Check Art in the DB */ if (albumCoverPath == null) { albumCoverPath = albumCursor .getString(albumCursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ART)); /* check if the embedded mp3 is valid (or big enough)*/ if (albumCoverPath != null) { Log.i("DBG", albumCoverPath); BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; Bitmap bmTmp = BitmapFactory.decodeFile(albumCoverPath, opts); if (opts == null || opts.outHeight < 320 || opts.outWidth < 320) albumCoverPath = null; if (bmTmp != null) bmTmp.recycle(); } } Log.i("DBG", "" + albumCoverPath); /* * If both checks above have failed return false */ return albumCoverPath; }
From source file:com.bamobile.fdtks.util.Tools.java
public static Bitmap getBitmapFromURL(Context context, String imageUrl, int width, int height) { if (imageUrl != null && imageUrl.length() > 0) { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(imageUrl.replace(" ", "%20")); try {//from w w w .j a v a 2s . c o m HttpResponse response = client.execute(get); byte[] content = EntityUtils.toByteArray(response.getEntity()); //get the dimensions of the image BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(content, 0, content.length, opts); // get the image and scale it appropriately opts.inJustDecodeBounds = false; opts.inSampleSize = Math.max(opts.outWidth / width, opts.outHeight / height); Bitmap bitmap = BitmapFactory.decodeByteArray(content, 0, content.length, opts); if (bitmap == null) { return null; } int scaledWidth = bitmap.getWidth(); int scaledHeight = bitmap.getHeight(); if (scaledWidth < scaledHeight) { float scale = width / (float) scaledWidth; scaledWidth = width; scaledHeight = (int) Math.ceil(scaledHeight * scale); if (scaledHeight < height) { scale = height / (float) scaledHeight; scaledHeight = height; scaledWidth = (int) Math.ceil(scaledWidth * scale); } } else { float scale = height / (float) scaledHeight; scaledHeight = height; scaledWidth = (int) Math.ceil(scaledWidth * scale); if (scaledWidth < width) { scale = width / (float) scaledWidth; scaledWidth = width; scaledHeight = (int) Math.ceil(scaledHeight * scale); } } Bitmap bmp = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, false); bitmap.recycle(); bitmap = null; return bmp; } catch (Exception e) { e.printStackTrace(); } } return null; }
From source file:com.aimfire.gallery.cardboard.PhotoActivity.java
public Bitmap toGrayscale(Bitmap bmpOriginal) { int width, height; height = bmpOriginal.getHeight();/*ww w.j av a 2 s . com*/ width = bmpOriginal.getWidth(); Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); Canvas c = new Canvas(bmpGrayscale); Paint paint = new Paint(); ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); paint.setColorFilter(f); c.drawBitmap(bmpOriginal, 0, 0, paint); bmpOriginal.recycle(); return bmpGrayscale; }
From source file:cw.kop.autobackground.files.DownloadThread.java
private void writeToFile(Bitmap image, String saveData, File file) { if (file.isFile()) { file.delete();/* ww w. j a v a 2 s. c o m*/ } FileOutputStream out = null; try { out = new FileOutputStream(file); image.compress(Bitmap.CompressFormat.PNG, 90, out); AppSettings.setUrl(file.getName(), saveData); Log.i(TAG, file.getName() + " " + saveData); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (Throwable e) { e.printStackTrace(); } } image.recycle(); }
From source file:com.wellsandwhistles.android.redditsp.reddit.prepared.RedditPreparedPost.java
private void downloadThumbnail(final Context context, final int widthPixels, final CacheManager cm, final int listId) { final String uriStr = src.getThumbnailUrl(); final URI uri = General.uriFromString(uriStr); final int priority = Constants.Priority.THUMBNAIL; final int fileType = Constants.FileType.THUMBNAIL; final RedditAccount anon = RedditAccountManager.getAnon(); cm.makeRequest(new CacheRequest(uri, anon, null, priority, listId, DownloadStrategyIfNotCached.INSTANCE, fileType, CacheRequest.DOWNLOAD_QUEUE_IMMEDIATE, false, false, context) { @Override/*from www .j ava2 s.c o m*/ protected void onDownloadNecessary() { } @Override protected void onDownloadStarted() { } @Override protected void onCallbackException(final Throwable t) { // TODO handle -- internal error throw new RuntimeException(t); } @Override protected void onFailure(final @CacheRequest.RequestFailureType int type, final Throwable t, final Integer status, final String readableMessage) { } @Override protected void onProgress(final boolean authorizationInProgress, final long bytesRead, final long totalBytes) { } @Override protected void onSuccess(final CacheManager.ReadableCacheFile cacheFile, final long timestamp, final UUID session, final boolean fromCache, final String mimetype) { try { synchronized (singleImageDecodeLock) { BitmapFactory.Options justDecodeBounds = new BitmapFactory.Options(); justDecodeBounds.inJustDecodeBounds = true; BitmapFactory.decodeStream(cacheFile.getInputStream(), null, justDecodeBounds); final int width = justDecodeBounds.outWidth; final int height = justDecodeBounds.outHeight; int factor = 1; while (width / (factor + 1) > widthPixels && height / (factor + 1) > widthPixels) factor *= 2; BitmapFactory.Options scaledOptions = new BitmapFactory.Options(); scaledOptions.inSampleSize = factor; final Bitmap data = BitmapFactory.decodeStream(cacheFile.getInputStream(), null, scaledOptions); if (data == null) return; thumbnailCache = ThumbnailScaler.scale(data, widthPixels); if (thumbnailCache != data) data.recycle(); } if (thumbnailCallback != null) thumbnailCallback.betterThumbnailAvailable(thumbnailCache, usageId); } catch (OutOfMemoryError e) { // TODO handle this better - disable caching of images Log.e("RedditPreparedPost", "Out of memory trying to download image"); e.printStackTrace(); } catch (Throwable t) { // Just ignore it. } } }); }
From source file:com.irccloud.android.activity.LoginActivity.java
@Override public 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, 0xff0b2e60));//www .j a v a 2 s . co m cloud.recycle(); } requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); setContentView(R.layout.activity_login); loading = findViewById(R.id.loading); connecting = findViewById(R.id.connecting); connectingMsg = (TextView) findViewById(R.id.connectingMsg); progressBar = (ProgressBar) findViewById(R.id.connectingProgress); loginHint = (LinearLayout) findViewById(R.id.loginHint); signupHint = (LinearLayout) findViewById(R.id.signupHint); hostHint = (TextView) findViewById(R.id.hostHint); login = findViewById(R.id.login); name = (EditText) findViewById(R.id.name); if (savedInstanceState != null && savedInstanceState.containsKey("name")) name.setText(savedInstanceState.getString("name")); email = (AutoCompleteTextView) findViewById(R.id.email); if (BuildConfig.ENTERPRISE) email.setHint(R.string.email_enterprise); ArrayList<String> accounts = new ArrayList<String>(); AccountManager am = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE); for (Account a : am.getAccounts()) { if (a.name.contains("@") && !accounts.contains(a.name)) accounts.add(a.name); } if (accounts.size() > 0) email.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, accounts.toArray(new String[accounts.size()]))); if (savedInstanceState != null && savedInstanceState.containsKey("email")) email.setText(savedInstanceState.getString("email")); password = (EditText) findViewById(R.id.password); password.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { new LoginTask().execute((Void) null); return true; } return false; } }); if (savedInstanceState != null && savedInstanceState.containsKey("password")) password.setText(savedInstanceState.getString("password")); host = (EditText) findViewById(R.id.host); if (BuildConfig.ENTERPRISE) host.setText(NetworkConnection.IRCCLOUD_HOST); else host.setVisibility(View.GONE); host.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { new LoginTask().execute((Void) null); return true; } return false; } }); if (savedInstanceState != null && savedInstanceState.containsKey("host")) host.setText(savedInstanceState.getString("host")); else host.setText(getSharedPreferences("prefs", 0).getString("host", BuildConfig.HOST)); if (host.getText().toString().equals("api.irccloud.com") || host.getText().toString().equals("www.irccloud.com")) host.setText(""); loginBtn = (Button) findViewById(R.id.loginBtn); loginBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new LoginTask().execute((Void) null); } }); loginBtn.setFocusable(true); loginBtn.requestFocus(); sendAccessLinkBtn = (Button) findViewById(R.id.sendAccessLink); sendAccessLinkBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { new ResetPasswordTask().execute((Void) null); } }); nextBtn = (Button) findViewById(R.id.nextBtn); nextBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (host.getText().length() > 0) { NetworkConnection.IRCCLOUD_HOST = host.getText().toString(); trimHost(); new EnterpriseConfigTask().execute((Void) null); } } }); TOS = (TextView) findViewById(R.id.TOS); TOS.setMovementMethod(new LinkMovementMethod()); forgotPassword = (TextView) findViewById(R.id.forgotPassword); forgotPassword.setOnClickListener(forgotPasswordClickListener); enterpriseLearnMore = (TextView) findViewById(R.id.enterpriseLearnMore); enterpriseLearnMore.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (isPackageInstalled("com.irccloud.android", LoginActivity.this)) { startActivity(getPackageManager().getLaunchIntentForPackage("com.irccloud.android")); } else { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.irccloud.android"))); } catch (Exception e) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.irccloud.android"))); } } } private boolean isPackageInstalled(String packagename, Context context) { PackageManager pm = context.getPackageManager(); try { pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES); return true; } catch (NameNotFoundException e) { return false; } } }); enterpriseHint = (LinearLayout) findViewById(R.id.enterpriseHint); EnterYourEmail = (TextView) findViewById(R.id.enterYourEmail); signupHint.setOnClickListener(signupHintClickListener); loginHint.setOnClickListener(loginHintClickListener); signupBtn = (Button) findViewById(R.id.signupBtn); signupBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { new LoginTask().execute((Void) null); } }); TextView version = (TextView) findViewById(R.id.version); try { version.setText("Version " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName); } catch (NameNotFoundException e) { version.setVisibility(View.GONE); } Typeface LatoRegular = Typeface.createFromAsset(getAssets(), "Lato-Regular.ttf"); Typeface LatoLightItalic = Typeface.createFromAsset(getAssets(), "Lato-LightItalic.ttf"); for (int i = 0; i < signupHint.getChildCount(); i++) { View v = signupHint.getChildAt(i); if (v instanceof TextView) { ((TextView) v).setTypeface(LatoRegular); } } for (int i = 0; i < loginHint.getChildCount(); i++) { View v = loginHint.getChildAt(i); if (v instanceof TextView) { ((TextView) v).setTypeface(LatoRegular); } } LinearLayout IRCCloud = (LinearLayout) findViewById(R.id.IRCCloud); for (int i = 0; i < IRCCloud.getChildCount(); i++) { View v = IRCCloud.getChildAt(i); if (v instanceof TextView) { ((TextView) v).setTypeface(LatoRegular); } } notAProblem = (LinearLayout) findViewById(R.id.notAProblem); for (int i = 0; i < notAProblem.getChildCount(); i++) { View v = notAProblem.getChildAt(i); if (v instanceof TextView) { ((TextView) v).setTypeface((i == 0) ? LatoRegular : LatoLightItalic); } } loginSignupHint = (LinearLayout) findViewById(R.id.loginSignupHint); for (int i = 0; i < loginSignupHint.getChildCount(); i++) { View v = loginSignupHint.getChildAt(i); if (v instanceof TextView) { ((TextView) v).setTypeface(LatoRegular); ((TextView) v).setOnClickListener((i == 0) ? loginHintClickListener : signupHintClickListener); } } name.setTypeface(LatoRegular); email.setTypeface(LatoRegular); password.setTypeface(LatoRegular); host.setTypeface(LatoRegular); loginBtn.setTypeface(LatoRegular); signupBtn.setTypeface(LatoRegular); TOS.setTypeface(LatoRegular); EnterYourEmail.setTypeface(LatoRegular); hostHint.setTypeface(LatoLightItalic); if (BuildConfig.ENTERPRISE) { name.setVisibility(View.GONE); email.setVisibility(View.GONE); password.setVisibility(View.GONE); loginBtn.setVisibility(View.GONE); signupBtn.setVisibility(View.GONE); TOS.setVisibility(View.GONE); signupHint.setVisibility(View.GONE); loginHint.setVisibility(View.GONE); forgotPassword.setVisibility(View.GONE); loginSignupHint.setVisibility(View.GONE); EnterYourEmail.setVisibility(View.GONE); sendAccessLinkBtn.setVisibility(View.GONE); notAProblem.setVisibility(View.GONE); enterpriseLearnMore.setVisibility(View.VISIBLE); enterpriseHint.setVisibility(View.VISIBLE); host.setVisibility(View.VISIBLE); nextBtn.setVisibility(View.VISIBLE); hostHint.setVisibility(View.VISIBLE); host.requestFocus(); } if (savedInstanceState != null && savedInstanceState.containsKey("signup") && savedInstanceState.getBoolean("signup")) { signupHintClickListener.onClick(null); } if (savedInstanceState != null && savedInstanceState.containsKey("login") && savedInstanceState.getBoolean("login")) { loginHintClickListener.onClick(null); } if (savedInstanceState != null && savedInstanceState.containsKey("forgotPassword") && savedInstanceState.getBoolean("forgotPassword")) { forgotPasswordClickListener.onClick(null); } mResolvingError = savedInstanceState != null && savedInstanceState.getBoolean("resolving_error", false); mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Auth.CREDENTIALS_API) .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build(); }
From source file:com.tealeaf.TeaLeaf.java
private Bitmap rotateBitmap(Bitmap bitmap, int rotate) { // rotate as needed Bitmap bmp;//from w ww. j ava 2 s.c om //only allow the largest size to be 768 for now, several phones //including the galaxy s3 seem to crash with rotating very large //images (out of memory errors) from the gallery int w = bitmap.getWidth(); int h = bitmap.getHeight(); Bitmap scaled = bitmap; if (w > h && w > 768) { float ratio = 768.f / (float) w; w = 768; h = (int) (ratio * h); scaled = Bitmap.createScaledBitmap(bitmap, w, h, true); if (bitmap != scaled) { bitmap.recycle(); } } if (h > w && h > 768) { float ratio = 768.f / (float) h; h = 768; w = (int) (ratio * w); scaled = Bitmap.createScaledBitmap(bitmap, w, h, true); if (bitmap != scaled) { bitmap.recycle(); } } int newWidth = scaled.getWidth(); int newHeight = scaled.getHeight(); int degrees = 0; if (rotate == ROTATE_90 || rotate == ROTATE_270) { newWidth = scaled.getHeight(); newHeight = scaled.getWidth(); } Matrix matrix = new Matrix(); matrix.postRotate(rotate); bmp = Bitmap.createBitmap(scaled, 0, 0, scaled.getWidth(), scaled.getHeight(), matrix, true); if (scaled != bmp) { scaled.recycle(); } return bmp; }