Reputation: 10110
I'm trying to convert this java code to python:
BufferedImage image;
FileInputStream fstream1 = new FileInputStream("image.png")
image = ImageIO.read(fstream1);
int max = -40000000; //Java rgb returns negative values
for (int i = 0; i < 128; i++)
{
for (int j = 0; j < 255; j++)
{
color = image.getRGB(j, i); //returns integer
.....
I tried this in python:
from PIL import Image
image = Image.open("image.png").convert("RGBA")
pixels = image.load()
for i in range(128):
for j in range(255):
color = pixels[j, i] #returns (R, G, B, A);
The problem however is that i'm getting different values in python.
Why does java returns negative integer values and how do i get the same result in python?
Upvotes: 0
Views: 1912
Reputation: 1121914
The Java getRGB()
value is a signed 32-bit integer with the alpha, R, G and B values in each of the 8 bits from most to least significant bytes.
You can 'reproduce' the same value with:
def packRGBA(r, g, b, a)
val = a << 24 | r << 16 | g << 8 | b
if a & 0x80:
val -= 0x100000000
return val
color = packRGBA(*pixels[j, i])
Upvotes: 1
Reputation: 58868
This function should convert a colour from the Python format to the Java format:
def convertPixel(c):
x = c[0] << 16 | c[1] << 8 | c[2] | c[3] << 24
if x >= 1<<31:
x -= 1<<32
return x
Note that Python's format is perfectly sane - it gives you the exact R, G, B and A values directly. It's Java that has the weird format.
You get negative values in Java because of integer overflow - for example 0xFFFFFFFF
(or 4294967295), which is pure white, wraps around to -1.
Upvotes: 1