7

My home automation app has a feature where people can upload images to their phone with floorplans and dashboards that they can use to control their home automation software. I have them upload two images: one visible image with the graphics that they want displayed, and a second color map with solid colors corresponding to the objects they want to target areas from the visible image. Both images have to be the same size, pixel-wise. When they tap the screen, I want to be able to get the color from the colormap overlay, and then I proceed to do what ever action has been associated with that color. The problem is, the scaling of the image is screwing me up. The images that they use can be larger than the device screen, so I scale them so they will fit within the display. I don't really need pinch to zoom capability right now, but I might implement it later. For now, I just want the image to be displayed at the largest size so it fits on the screen. So, my question is, how could I modify this code so that I can get the correct touchpoint color from the scaled image. The image scaling itself seems to be working fine. It is scaled and displays correctly. I just can't get the right touchpoint.

 final Bitmap bm = decodeSampledBitmapFromFile(visible_image, size, size);
 if (bm!=null) {
    imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    imageview.setImageBitmap(bm);
 }

 final Bitmap bm2 = decodeSampledBitmapFromFile(image_overlay, size, size);
 if (bm2!=null) {
    overlayimageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    overlayimageview.setImageBitmap(bm2);

    imageview.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent mev) {
            DecodeActionDownEvent(v, mev, bm2);
            return false;
        }

    });
 }

 private void DecodeActionDownEvent(View v, MotionEvent ev, Bitmap bm2)
 {
    xCoord = Integer.valueOf((int)ev.getRawX());
    yCoord = Integer.valueOf((int)ev.getRawY());
    try {
        // Here's where the trouble is.
        // returns the value of the unscaled pixel at the scaled touch point?
        colorTouched = bm2.getPixel(xCoord, yCoord); 
    } catch (IllegalArgumentException e) {
        colorTouched = Color.WHITE; // nothing happens when touching white
    }
 }

 private static Bitmap decodeSampledBitmapFromFile(String fileName, 
         int reqWidth, int reqHeight) {
     // code from 
     // http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
     final BitmapFactory.Options options = new BitmapFactory.Options();
     options.inJustDecodeBounds = true;
     BitmapFactory.decodeFile(fileName, options);

     // Calculate inSampleSize
     options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

     // Decode bitmap with inSampleSize set
     options.inJustDecodeBounds = false;
     return BitmapFactory.decodeFile(fileName, options);
 }

 private static int calculateInSampleSize(
      BitmapFactory.Options options, int reqWidth, int reqHeight) {
     // code from 
     // http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
     // Raw height and width of image
     final int height = options.outHeight;
     final int width = options.outWidth;
     int inSampleSize = 1;

     if (height > reqHeight || width > reqWidth) {
       if (width > height) {
          inSampleSize = Math.round((float)height / (float)reqHeight);
       } else {
          inSampleSize = Math.round((float)width / (float)reqWidth);
       }
     }
     return inSampleSize;
 }

2 Answers 2

31

I figured it out. I replaced

 xCoord = Integer.valueOf((int)ev.getRawX());
 yCoord = Integer.valueOf((int)ev.getRawY());

with

 Matrix inverse = new Matrix();
 v.getImageMatrix().invert(inverse);
 float[] touchPoint = new float[] {ev.getX(), ev.getY()};
 inverse.mapPoints(touchPoint);
 xCoord = Integer.valueOf((int)touchPoint[0]);
 yCoord = Integer.valueOf((int)touchPoint[1]);
3
  • 3
    Fantastic! using getPixel(xCoord,yCoord) now returns accurate colors! ((BitmapDrawable)mImageView.getDrawable()).getBitmap().getPixel(xCoord,yCoord) Nov 10, 2013 at 2:24
  • And please explaing the reverse mapping, new x,y to old xy Mar 14, 2017 at 7:12
  • Excellent answer! Thank you. Dec 29, 2019 at 19:24
1

After 7 years I have to provide another answer, because after upgrading to LG G8s from LG G6 the code from accepted answer stopped returning the correct color.

This solution works on all the phones I found at home, but who knows... maybe even this one is not universal.

(Using Xamarin C# but the principle is easy to understand)

First we have to get the actual ImageView size as float to get floating point division

private float imageSizeX;
private float imageSizeY;

private void OnCreate(...) {
    ...
    FindViewById<ImageView>(Resource.Id.colpick_Image).LayoutChange += OnImageLayout;
    FindViewById<ImageView>(Resource.Id.colpick_Image).Touch += Image_Touch;
    ...
}

//Event called every time the layout of our ImageView is updated
private void OnImageLayout(object sender, View.LayoutChangeEventArgs e) {
    imageSizeX = Image.Width;
    imageSizeY = Image.Height;
    Image.LayoutChange -= OnImageLayout; //Just need it once then unsubscribe
}
//Called every time user touches/is touching the ImageView
private void Image_Touch(object sender, View.TouchEventArgs e) {
    MotionEvent m = e.Event;

    ImageView img = sender as ImageView;

    int x = Convert.ToInt32(m.GetX(0));
    int y = Convert.ToInt32(m.GetY(0));

    Bitmap bmp = (img.Drawable as BitmapDrawable).Bitmap;

    // The scale value (how many times is the image bigger)
    // I only use it with images where Width == Height, so I get
    // scaleX == scaleY
    float scaleX = bmp.Width / imageSizeX;
    float scaleY = bmp.Height / imageSizeY;

    x = (int)(x * scaleX);
    y = (int)(y * scaleY);

    // Check for invalid values/outside of image bounds etc...

    // Get the correct Color ;)
    int color = bmp.GetPixel(x, y);
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.