links to this page:    
View this PageEdit this PageUploads to this PageHistory of this PageTop of the SwikiRecent ChangesSearch the SwikiHelp Guide
Recipe: Access a JPEG file pixel by pixel
Last updated at 7:08 am UTC on 9 August 2017

How do I access a jpeg file pixel by pixel? For example to build a histogram of the image.


You can get a Form using:

     f := Form fromFileNamed: 'my_image_file.jpg'.

This is a 32-bit-per-pixel form, stored as 4 8-bit color components (alpha, red, green, blue). To get the raw pixel bits:

     pixels := f bits.

You can then do a histogram something like:

 redHist := Bag new.
 greenHist := Bag new.
 blueHist := Bag new.

 pixels do:
     [:pel |
     redHist add: ((pel bitShift: -16) bitAnd: 255).
     greenHist add: ((pel bitShift: -8) bitAnd: 255).
     blueHist add: (pel bitAnd: 255)].

Date: Fri, 29 Jun 2001 08:55:58 -0500
From: Tim Olson

This didn't really work for me and wasn't all that intuitive...after an afternoon of digging around, I found that you can do this:

     f := Form fromFileNamed: 'my_image_file.jpg'.
     aColor := f colorAt: 0@0. "top-left pixel"

Note that the pixel locations start at 0@0 (NOT 1@1 as I had assumed).

You can then access the red, green and blue elements of aColor like so:

     red   := aColor red. 
     green := aColor green. 
     blue  := aColor blue. 

I find this a lot easier since there is no bit arithmatic involved.

Hope this helps someone!
Lushil January 23, 2002

colorAt works for any depth or kind of form, and it's simple, but it is a bit slow. As long as you aren't doing speed critical mass pixel manipulation, it should be fine, but be aware there faster methods dealing more directly for the form data. You'll have to check out the image, because I avoided them! For what I do, taking 3 seconds to process the image instead of 1 is ok.
Eddie Cottongim