Byte Array to Image Object

Getting an Image object from a byte array

You'd use a MemoryStream to do this:

byte[] bytes;
...
using (var ms = new System.IO.MemoryStream(bytes)) {
using(var img = Image.FromStream(ms)) {
...
}
}

Convert from byte array to Image

You can try fromarray function

import numpy as np
image = Image.fromarray(np.array(ba).reshape(498,1))

Byte Array to Image object

BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));

How to convert a byte array into an image?

I realize this is an old thread, but I managed to do this through an AJAX call on a web service and thought I'd share...

  • I have an image in my page already:

     <img id="ItemPreview" src="" />
  • AJAX:

    $.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    timeout: 10000,
    url: 'Common.asmx/GetItemPreview',
    data: '{"id":"' + document.getElementById("AwardDropDown").value + '"}',
    success: function (data) {
    if (data.d != null) {
    var results = jQuery.parseJSON(data.d);
    for (var key in results) {
    //the results is a base64 string. convert it to an image and assign as 'src'
    document.getElementById("ItemPreview").src = "data:image/png;base64," + results[key];
    }
    }
    }
    });

My 'GetItemPreview' code queries a SQL server where I have an image stored as a base64 string and returns that field as the 'results':

     string itemPreview = DB.ExecuteScalar(String.Format("SELECT [avatarImage] FROM [avatar_item_template] WHERE [id] = {0}", DB.Sanitize(id)));
results.Add("Success", itemPreview);
return json.Serialize(results);

The magic is in the AJAX call at this line:

     document.getElementById("ItemPreview").src = "data:image/png;base64," + results[key];

Enjoy!

PIL: Convert Bytearray to Image

If you manipulate with bytearrays, then you have to use io.BytesIO. Also you can read a file directly to a bytearray.

import os
import io
import PIL.Image as Image

from array import array

def readimage(path):
count = os.stat(path).st_size / 2
with open(path, "rb") as f:
return bytearray(f.read())

bytes = readimage(path+extension)
image = Image.open(io.BytesIO(bytes))
image.save(savepath)

Getting Object from database containing byte array image

You should take a look at the community project Spring Content. This project gives you a Spring Data API and development approach to content. It is to unstructured data (documents, images, videos, etc), what Spring Data is to structured data. You could add it with something like the following:-

pom.xml (Spring Boot starters also available)

   <!-- Java API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-jpa</artifactId>
<version>0.11.0</version>
</dependency>
<!-- REST API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-rest</artifactId>
<version>0.11.0</version>
</dependency>

Configuration

@Configuration
@EnableJpaStores
@Import("org.springframework.content.rest.config.RestConfiguration.class") <!-- enables REST API)
public class ContentConfig {

<!-- specify the resource specific to your database -->
@Value("/org/springframework/content/jpa/schema-drop-h2.sql")
private ClasspathResource dropBlobTables;

<!-- specify the resource specific to your database -->
@Value("/org/springframework/content/jpa/schema-h2.sql")
private ClasspathResource createBlobTables;

@Bean
DataSourceInitializer datasourceInitializer() {
ResourceDatabasePopulator databasePopulator =
new ResourceDatabasePopulator();

databasePopulator.addScript(dropBlobTables);
databasePopulator.addScript(createBlobTables);
databasePopulator.setIgnoreFailedDrops(true);

DataSourceInitializer initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource());
initializer.setDatabasePopulator(databasePopulator);

return initializer;
}
}

NB: this configuration is not needed if you use the relevant Spring Boot starter.

To associate content, add Spring Content annotations to your Image entity.

Post.java

@Entity
public class Post {

...

@OneToOne
private Image image;

Image.java

@Entity
public class Image {

// replace @Lob/byte array field with:

@ContentId
private String contentId;

@ContentLength
private long contentLength = 0L;

@MimeType
private String mimeType;

Create a "store" for your images:

ImageContentStore.java

public interface ImageContentStore extends ContentStore<Image, String> {
}

This is all you need to create REST endpoints @ /image/{imageId}. When your application starts, Spring Content will look at your dependencies (seeing Spring Content JPA/REST), look at your ImageContentStore interface and inject an implementation of that interface for JPA. It will also inject a @Controller that forwards http requests to that implementation. This saves you having to implement any of this yourself.

So...

curl -X POST /image/{imageId} -F 'data=@path/to/local/file'

will store the content of file path/to/local/file in the database and associate it with the post entity whose id is postId.

curl /image/{imageId}

will fetch it again and so on...supports full CRUD.

There are a couple of getting started guides and videos here. The reference guide is here.

HTH

How to convert image to byte array

Sample code to change an image into a byte array

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms,imageIn.RawFormat);
return ms.ToArray();
}
}

C# Image to Byte Array and Byte Array to Image Converter Class



Related Topics



Leave a reply



Submit