1
$\begingroup$

I was trying to generate an image from a list of bytes so I only had to Import an Image once as I want to store a Base64Encoded string in a database using the Imported bytes.

I found one solution but not sure why ImportByteArray is needed when generating an Image from bytes?

image = Import[
  "http://www.wolfram.com/common/framework/img/spikey.en.png", "Image"]

imageBytes = 
 Import["http://www.wolfram.com/common/framework/img/spikey.en.png", 
  "Byte"]

imageBinary = 
 Import["http://www.wolfram.com/common/framework/img/spikey.en.png", 
  "Binary"]

imageBytes === imageBinary 
(*true*)

imageBytes === Normal[BinarySerialize[image]]
(*False*)

To Generate Image from bytes, one solution is:

decodedImage = Image[ImportByteArray[ByteArray[imageBytes]], "Byte"]

decodedImage === image
(*True*)

Why do you need the ImportByteArray? You should be able to:

imageData = Image[imageBytes, "Byte"]
(*ERROR Image::imgarray*)

This also does not work:

imageData = Image[ByteArray[imageBytes], "Byte"]
$\endgroup$
4
$\begingroup$

There are a couple of issues here. First, the full text of Image::imgarray sheds light on one issue:

Image::imgarray: The specified argument ByteArray[2.3 kB] should be an array of rank 2 or 3 with machine-sized numbers.

Specifically, Image does not know how to turn a vector of numbers into a matrix. Second, and more interestingly, Image does not work with image formats, but the equivalent, underlying data. Simply, imageBytes is still in its original format

In[14]:= ByteArrayFormat@ByteArray[imageBytes]
Out[14]= "PNG"

So, ImportByteArray is needed to convert this from formatted data to raw data.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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