Convert Drawable to PImage example

In case someone needs it.
It took me ages to get that working on APDE.

Any suggestions for improvement are welcome,
since I’m sure there’s a better way to do it.

Cheers, AmyS3


import android.graphics.drawable.Drawable;
import android.graphics.Bitmap;
import android.graphics.Canvas;

void setup()
{
  fullScreen();
  /*
  example use:
  Pimage image = drawableToPImage(your_drawable);
  */
}

void draw(){
}

public PImage drawableToPImage(Drawable drawable)
{
  // first convert to bitmap
  int widthPixels =drawable.getIntrinsicWidth();
  int heightPixels = drawable.getIntrinsicHeight();
  Bitmap bitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(bitmap);
  drawable.setBounds(0, 0, widthPixels, heightPixels);
  drawable.draw(canvas);
  // now into PImage
  PImage img=new PImage(widthPixels, heightPixels, PConstants.ARGB);
  bitmap.getPixels(img.pixels, 0, img.width, 0, 0, img.width, img.height);
  img.updatePixels();
  return img;
}
1 Like

Updated with a function to convert from Drawable to PImage.

Since I’ve been searching for ages to get that working on APDE, because pretty much every answer to this problem that you find on the web doesn’t work on APDE, i now post the solution that actually works here so you don’t have to melt your brain as well.
That goes for both functions…

Cheers, AmyS3

/**
  Example code to convert PImage to Drawable
  and vice-versa on APDE (processing).
  Note: the functions take objects and not filenames/paths/streams.
  AmyS3 2023 
*/

import android.graphics.drawable.Drawable; // needed for both
import android.graphics.Bitmap; // needed for both
import android.graphics.Canvas; // for Drawable to PImage
import android.widget.ImageView; // for PImage to Drawable

void setup()
{
  fullScreen();
  /*
  example use:
  PImage image = DrawableToPImage(your_Drawable);
  Drawable drawable = PImageToDrawable(your_PImage);
  */
}

void draw(){
}

public PImage DrawableToPImage(Drawable drawable)
{
  // first convert to bitmap
  int widthPixels =drawable.getIntrinsicWidth();
  int heightPixels = drawable.getIntrinsicHeight();
  Bitmap bitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(bitmap);
  drawable.setBounds(0, 0, widthPixels, heightPixels);
  drawable.draw(canvas);
  // now into PImage
  PImage image=new PImage(widthPixels, heightPixels, PConstants.ARGB);
  bitmap.getPixels(image.pixels, 0, image.width, 0, 0, image.width, image.height);
  image.updatePixels();
  return image;
}


public Drawable PImageToDrawable(PImage image)
{
  // first load PImage into an ImageView
  ImageView imgView = new ImageView(this.getActivity());
  imgView.setImageBitmap((Bitmap)image.getNative());
  imgView.buildDrawingCache();
  // now extract the drawable
  Drawable drawable = imgView.getDrawable();
  return drawable;
}