Skip to content

Read an Image From Memory

Edison Hua edited this page Jan 27, 2024 · 4 revisions

Chances are, if you are reading this page, you have a pointer to memory and would like to convert it to an image.

So that means your pointer is very likely not going to be a:

  • IStream
  • IRandomAccessStream
  • pBitmap

but rather some pointer p and its size.

Pointer to Pixel Data

Given a pointer to pixel data, a 2-D shape is required to be interpreted as image data. All pixels are assumed to be 32-bit ARGB by default in the format of 0xAARRGGBB.

; Shapes the buffer into an 800x800 image. The user defines ptr and size.
buffer := ImagePutBuffer({ptr: ptr, size: size, width: 800, height: 800, stride:800*4})

Internally, ImagePut.from_buffer(shape) is called and creates a pBitmap from the given width, height, and stride. You may call from_buffer directly to get a pBitmap to avoid any redundant memory copies. Calling pBitmap := ImagePutBitmap(shape) returns a cloned bitmap.

Because ImagePut is smart, it's possible to make do with less information. For example, the stride can be omitted, leaving just the width and height.

Choose one of the of following representations:

  1. ptr, size, width, height, stride
  2. ptr, (optional size), width, height
  3. ptr, (optional size), stride, height
  4. ptr, size, width
  5. ptr, size, height
  6. ptr, size, stride

Note that any missing parameters such as (size) can be calculated from the other existing values.

buf := ImagePutBuffer("https://picsum.photos/800")
ptr := buf.ptr
size := buf.size

ImagePutWindow({ptr: ptr, size: size, width: 800, height: 800, stride:800*4}, 1)
ImagePutWindow({ptr: ptr, width: 800, height: 800}, 2)
ImagePutWindow({ptr: ptr, height: 800, stride:800*4}, 3)
ImagePutWindow({ptr: ptr, size: size, width: 800}, 4)
ImagePutWindow({ptr: ptr, size: size, height: 800}, 5)
ImagePutWindow({ptr: ptr, size: size, stride:800*4}, 6)

In other words, a buffer object is a valid image if it contains the ptr and size properties and at least one of the following: stride, width, or height. This simplifies conversion of a buffer's contents to an image.