Example usage for android.graphics Bitmap hasAlpha

List of usage examples for android.graphics Bitmap hasAlpha

Introduction

In this page you can find the example usage for android.graphics Bitmap hasAlpha.

Prototype

public final boolean hasAlpha() 

Source Link

Document

Returns true if the bitmap's config supports per-pixel alpha, and if the pixels may contain non-opaque alpha values.

Usage

From source file:Main.java

/**
 * Convert the Bitmap to ALPHA_8.  The old one will be recycled.
 *///from w ww . j  ava 2s  .c  o m
static Bitmap toAlpha8(Bitmap src, boolean recycle) {
    if (!src.hasAlpha()) {
        src = redToAlpha(src, recycle);
        recycle = true;
    }

    Bitmap dest = src.copy(Bitmap.Config.ALPHA_8, false);
    if (recycle)
        src.recycle();
    return dest;
}

From source file:Main.java

/**
 * Add an alpha channel to the given image if it does not already have one.
 * /*from w w w. ja v  a  2s. com*/
 * @param image
 *            the image to add an alpha channel to.
 * @return a copy of the given image with an alpha channel. If the image already have the alpha channel, return the
 *         image itself.
 */
public static Bitmap imageWithAlpha(Bitmap image) {
    if (image == null) {
        return null;
    }
    if (image.hasAlpha()) {
        return image;
    }
    return image.copy(Bitmap.Config.ARGB_8888, true);
}

From source file:Main.java

public static int getDominantColor(Bitmap bitmap) {
    if (null == bitmap)
        return Color.TRANSPARENT;

    int redBucket = 0;
    int greenBucket = 0;
    int blueBucket = 0;
    int alphaBucket = 0;

    boolean hasAlpha = bitmap.hasAlpha();
    int pixelCount = bitmap.getWidth() * bitmap.getHeight();
    int[] pixels = new int[pixelCount];
    bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

    for (int y = 0, h = bitmap.getHeight(); y < h; y++) {
        for (int x = 0, w = bitmap.getWidth(); x < w; x++) {
            int color = pixels[x + y * w]; // x + y * barHeight
            redBucket += (color >> 16) & 0xFF; // Color.red
            greenBucket += (color >> 8) & 0xFF; // Color.greed
            blueBucket += (color & 0xFF); // Color.blue
            if (hasAlpha)
                alphaBucket += (color >>> 24); // Color.alpha
        }/*from  w ww . j  a  v a 2 s.  c  om*/
    }

    return Color.argb((hasAlpha) ? (alphaBucket / pixelCount) : 255, redBucket / pixelCount,
            greenBucket / pixelCount, blueBucket / pixelCount);
}

From source file:org.appcelerator.titanium.TiBlob.java

/**
 * Creates a blob from a bitmap./* w  ww . j a va2  s.com*/
 * @param image the image used to create blob.
 * @return new instance of TiBlob.
 * @module.api
 */
public static TiBlob blobFromImage(Bitmap image) {

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte data[] = new byte[0];
    if (image.hasAlpha()) {
        if (image.compress(CompressFormat.PNG, 100, bos)) {
            data = bos.toByteArray();
        }
    } else {
        if (image.compress(CompressFormat.JPEG, 100, bos)) {
            data = bos.toByteArray();
        }
    }

    TiBlob blob = new TiBlob(TYPE_IMAGE, data, "image/bitmap");
    blob.image = image;
    blob.width = image.getWidth();
    blob.height = image.getHeight();
    return blob;
}

From source file:fr.free.nrw.commons.media.MediaDetailFragment.java

private void displayMediaDetails(final Media media) {
    //Always load image from Internet to allow viewing the desc, license, and cats
    String actualUrl = media.getThumbnailUrl(640);
    if (actualUrl.startsWith("http")) {
        Log.d("Volley", "Actual URL starts with http and is: " + actualUrl);

        ImageLoader loader = ((CommonsApplication) getActivity().getApplicationContext()).getImageLoader();
        MediaWikiImageView mwImage = (MediaWikiImageView) image;
        mwImage.setLoadingView(loadingProgress); //FIXME: Set this as an attribute
        mwImage.setMedia(media, loader);

        // FIXME: For transparent images
        // FIXME: keep the spinner going while we load data
        // FIXME: cache this data
        // Load image metadata: desc, license, categories
        detailFetchTask = new AsyncTask<Void, Void, Boolean>() {
            private MediaDataExtractor extractor;

            @Override//from  ww w. j  a va2  s. c  o m
            protected void onPreExecute() {
                extractor = new MediaDataExtractor(media.getFilename(), licenseList);
            }

            @Override
            protected Boolean doInBackground(Void... voids) {
                try {
                    extractor.fetch();
                    return Boolean.TRUE;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return Boolean.FALSE;
            }

            @Override
            protected void onPostExecute(Boolean success) {
                detailFetchTask = null;

                if (success.booleanValue()) {
                    extractor.fill(media);

                    // Set text of desc, license, and categories
                    desc.setText(prettyDescription(media));
                    license.setText(prettyLicense(media));

                    categoryNames.removeAll(categoryNames);
                    categoryNames.addAll(media.getCategories());

                    categoriesLoaded = true;
                    categoriesPresent = (categoryNames.size() > 0);
                    if (!categoriesPresent) {
                        // Stick in a filler element.
                        categoryNames.add(getString(R.string.detail_panel_cats_none));
                    }
                    rebuildCatList();
                } else {
                    Log.d("Commons", "Failed to load photo details.");
                }
            }
        };
        Utils.executeAsyncTask(detailFetchTask);
    } else {
        //This should not usually happen, image along with associated details should always be loaded from Internet, but keeping this for now for backup.
        //Even if image is loaded from device storage, it will display, albeit with empty desc and cat.
        Log.d("Volley", "Actual URL does not start with http and is: " + actualUrl);
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(actualUrl, image,
                displayOptions, new ImageLoadingListener() {
                    public void onLoadingStarted(String s, View view) {
                        loadingProgress.setVisibility(View.VISIBLE);
                    }

                    public void onLoadingFailed(String s, View view, FailReason failReason) {
                        loadingProgress.setVisibility(View.GONE);
                        loadingFailed.setVisibility(View.VISIBLE);
                    }

                    public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                        loadingProgress.setVisibility(View.GONE);
                        loadingFailed.setVisibility(View.GONE);
                        image.setVisibility(View.VISIBLE);
                        if (bitmap.hasAlpha()) {
                            image.setBackgroundResource(android.R.color.white);
                        }

                        // Set text of desc, license, and categories
                        desc.setText(prettyDescription(media));
                        license.setText(prettyLicense(media));

                        categoryNames.removeAll(categoryNames);
                        categoryNames.addAll(media.getCategories());

                        categoriesLoaded = true;
                        categoriesPresent = (categoryNames.size() > 0);
                        if (!categoriesPresent) {
                            // Stick in a filler element.
                            categoryNames.add(getString(R.string.detail_panel_cats_none));
                        }
                        rebuildCatList();
                    }

                    public void onLoadingCancelled(String s, View view) {
                        Log.e("Volley", "Image loading cancelled. But why?");
                    }
                });
    }

    title.setText(media.getDisplayTitle());
    desc.setText(""); // fill in from network...
    license.setText(""); // fill in from network...
}

From source file:org.catrobat.paintroid.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {

    initLocaleConfiguration();//from   www .j a va2 s. com
    Configuration config = getApplicationContext().getResources().getConfiguration();
    PaintroidApplication.isRTL = (config.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);

    ColorPickerDialog.init(this);
    IndeterminateProgressDialog.init(this);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    initActionBar();
    mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    PaintroidApplication.catroidPicturePath = null;
    String catroidPicturePath = null;
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        catroidPicturePath = extras.getString(getString(R.string.extra_picture_path_catroid));

        Log.d(PaintroidApplication.TAG, "catroidPicturePath: " + catroidPicturePath);
    }
    if (catroidPicturePath != null) {
        PaintroidApplication.openedFromCatroid = true;
        if (!catroidPicturePath.equals("")) {
            PaintroidApplication.catroidPicturePath = catroidPicturePath;
            PaintroidApplication.scaleImage = false;
        }
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setDisplayHomeAsUpEnabled(true);
            supportActionBar.setDisplayShowHomeEnabled(true);
        }
    } else {
        PaintroidApplication.openedFromCatroid = false;
    }
    PaintroidApplication.orientation = getResources().getConfiguration().orientation;
    PaintroidApplication.drawingSurface = (DrawingSurface) findViewById(R.id.drawingSurfaceView);
    PaintroidApplication.perspective = new Perspective(PaintroidApplication.drawingSurface.getHolder());
    mDrawingSurfaceListener = new DrawingSurfaceListener();
    BrushPickerView.init(this);
    mBottomBar = new BottomBar(this);
    mTopBar = new TopBar(this, PaintroidApplication.openedFromCatroid);
    mLayerSideNav = (NavigationView) findViewById(R.id.nav_view_layer);
    mLayersAdapter = new LayersAdapter(this, PaintroidApplication.openedFromCatroid,
            PaintroidApplication.drawingSurface.getBitmapCopy());

    int colorPickerBackgroundColor = PaintroidApplication.colorPickerInitialColor;
    ColorPickerDialog.getInstance().setInitialColor(colorPickerBackgroundColor);

    PaintroidApplication.drawingSurface.setOnTouchListener(mDrawingSurfaceListener);

    if (PaintroidApplication.openedFromCatroid && catroidPicturePath != null
            && catroidPicturePath.length() > 0) {
        initializeWhenOpenedFromCatroid();

        loadBitmapFromUriAndRun(Uri.fromFile(new File(catroidPicturePath)), new RunnableWithBitmap() {
            @Override
            public void run(Bitmap bitmap) {
                if (!bitmap.hasAlpha()) {
                    bitmap.setHasAlpha(true);
                }
                handleAndAssignImage(bitmap);
            }

            private void handleAndAssignImage(Bitmap bitmap) {
                Command command = new LoadCommand(bitmap);
                PaintroidApplication.commandManager.commitCommandToLayer(
                        new LayerCommand(LayerListener.getInstance().getCurrentLayer()), command);

            }
        });

    } else if (PaintroidApplication.openedFromCatroid) {
        initializeWhenOpenedFromCatroid();
    } else {
        initialiseNewBitmap();
    }

    if (PaintroidApplication.openedFromCatroid == false)
        LayerListener.init(this, mLayerSideNav, PaintroidApplication.drawingSurface.getBitmapCopy(), false);

    if (!PaintroidApplication.commandManager.isCommandManagerInitialized()
            || PaintroidApplication.openedFromCatroid)
        initCommandManager();

    initNavigationDrawer();
    initKeyboardIsShownListener();
}

From source file:com.rokolabs.app.common.image.ImageCache.java

public void saveBitmapToDiskSync(String data, Bitmap bitmap) {
    if (data == null || bitmap == null) {
        return;/*from  w ww .j ava2  s  . c  o  m*/
    }

    synchronized (mDiskCacheLock) {
        // Add to disk cache
        if (mDiskLruCache != null) {
            final String key = hashKeyForDisk(data);
            OutputStream out = null;
            try {
                DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
                if (snapshot == null) {
                    final DiskLruCache.Editor editor = mDiskLruCache.edit(key);
                    if (editor != null) {
                        out = editor.newOutputStream(DISK_CACHE_INDEX);
                        if (bitmap.hasAlpha())
                            bitmap.compress(CompressFormat.PNG, 100, out);
                        else
                            bitmap.compress(mCacheParams.compressFormat, mCacheParams.compressQuality, out);
                        editor.commit();
                        out.close();
                    }
                } else {
                    snapshot.getInputStream(DISK_CACHE_INDEX).close();
                }
            } catch (final IOException e) {
                Log.e(TAG, "addBitmapToCache - " + e);
            } catch (Exception e) {
                Log.e(TAG, "addBitmapToCache - " + e);
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                }
            }
        }
    }
}