0

I want to get the pixel value from image not color.Android has int getPixel(x, y) method,Is there a similar implementation in iOS? Note that I want to get the pixel value, not the color.

2 Answers2

0

Answer available here. The linked answer returns a UIColor object, but that is created from the RGB data that is read, so it is available.

You can modify that answer to match Android's documentation:

The components are stored as follows (alpha << 24) | (red << 16) | (green << 8) | blue

red = rawData[byteIndex];
green = rawData[byteIndex + 1];
blue = rawData[byteIndex + 2];
alpha = rawData[byteIndex + 3];

NSInteger pixel = (alpha << 24) | (red << 16) | (green << 8) | blue; // 32 or 64bits depending on device
int32_t androidPixel = (int32_t)pixel; // Guaranteed 32 bits like android/java `int`

Note that although android's documentation implies this is an int, a color such as opaque black looks like 0xFF000000, meaning it will appear as a negative number in a 32 bit int. Using an unsigned integer or 64 bit integer will appear to have a different result although the bits are the same.

Community
  • 1
  • 1
arsenius
  • 12,090
  • 7
  • 58
  • 76
0

Getting pixel size is simple task. There two ways you can get image pixel size. Try one of the following method.

  1. Using cgImage

    let image = UIImage(named: "test")
    let width = image?.cgImage.width // Pixel width
    let height = image?.cgImage.height // Pixel height
    let imageSize = CGSize(width: width, height: height) //Image Pixel Size
    print("Image Pixel Size: \(imageSize)")
    
  2. Using PNG Data

    let image = UIImage(named: "test")
    let imageData: Data = UIImagePNGRepresentation(image)! // Get PNG Image Data
    let image: UIImage = UIImage(data: imageData)!  // Get image from PNG Data
    let  imageSize = image.size // Finally get size from png Image
    print("Image Pixel Size: \(imageSize)")
    
Jay
  • 106
  • 6