Converting an object with a System.Drawing.Image into a json format

I'm facing a bit of a challenge and struggling to find a solution...

Within my interface (and implemented class), there is an image property...

    Guid uid { get; set; }
    Image imageData1 { get; set; }
    string fileName { get; set; }

The image is stored in the database as a byte[] and retrieving it is not a problem as I deserialize it to a dynamic type and then populate the desired object using a custom conversion function that I created for byte[] to image conversion.

However, the issue lies in the reverse direction...

string tmpJson = JsonConvert.SerializeObject( IclassOjbect );

This method serializes the class name of the image but doesn't include the image data as a byte array.

I can convert the image data to a byte[] outside of serialization, but I'm unsure how to insert it into tmpJSON instead of the "image class name" without resorting to risky string manipulation...

Any suggestions or ideas on how to approach this?

Answer №1

Stumbled upon this while browsing the web, so I decided to share my insight, even though it's been a while:

[JsonIgnore]
public Image Picture { get; set; } = null;

public byte[] ConvertImageToBytes
{
    get
    {
        if (this.Picture != null)
        {
            using (var stream = new MemoryStream())
            {
                this.Picture.Save(stream, this.Picture.RawFormat);
                return stream.ToArray();
            }
        }

        return null;
    }

    set
    {
        if (value != null)
        {
            using (var stream = new MemoryStream(value))
            {
                this.Picture = Image.FromStream(stream);
            }
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking for a way to efficiently add multiple value inputs to a JSON object using jQuery or JavaScript?

Here is the HTML input tag code I am working with: <form id="info"> <input id="A" name="A" type="hidden" nodetye="parent" value="A"> <input id="A1" name="A1" type="text" nodetype="child" value="a1val"> <input id="A2" name ...

Discover a variety of web element types with FindElements() in Selenium using C#

Hello everyone, I could really use some assistance with a programming issue I am facing. I have a method where I check for the presence of multiple web objects on a page and then click on them if they are present. The method is currently working as expecte ...

Tips for creating JSON parser Entity Objects for Currency Converter API with this desired Output

I have a project in which I need to retrieve currency values from an external API converter at to perform conversions between different currencies. For example, if I use the endpoint , it will return the following data: { "rates": { "GBP": 0.761 ...

Guidelines on transforming a Java Object list into JSON format and displaying it through AJAX requests

Currently, I am facing an issue where I have a Java object list retrieved from the database as an ArrayList of objects. I need to display this on a JSP page using AJAX. While I know how to display an ArrayList of Strings via AJAX in a JSP page, I'm st ...

Converting JSONSchema into TypeScript: Creating a structure with key-value pairs of strings

I am working with json-schema-to-typescript and looking to define an array of strings. Currently, my code looks like this: "type": "object", "description": "...", "additionalProperties": true, "items": { "type": "string" ...

Having trouble sending a HTTP Post request to a Web Service from my Android Application

Working on an application that involves using both GET and POST requests to interact with Web Services. While the GET requests are working smoothly, encountering challenges with the POST requests. Have tried two different approaches in the code implementat ...

Check out the HTML display instead of relying on console.log

Need help displaying the result of a JavaScript statement in an HTML page instead of console.log output. I am new to coding! Here is the JS code snippet: $.ajax({ url: 'xml/articles.json', dataType: 'json', type: ...

Exploring data with JSON

I am currently working on integrating the Websters Dictionary into my Python code to easily look up word definitions. As suggested by Trigonom, I can search for the "shortdef" in the JSON data. @bot.command() async def define(ctx, *, search): with url ...

How can we reduce the size of JSON array messages?

When working with JSON to transmit an array of objects from the same class, I've noticed that the fields of the objects are repeated multiple times unnecessarily. This results in very long messages, especially for arrays with a large number of element ...

Customize JSON response formatting based on specific needs

When returning a JSON response to an API, I am utilizing the json_encode() method. The array includes a key for users that can contain multiple users, or be empty, and a key for course that can either be empty or contain a single object as shown below: { ...

I have a query regarding the load function and JSON

Is it feasible to achieve something similar to this? $.ajax({ url: "test.php", success: function(json, json1){ //I wonder if I can have more than one parameter here? $m0 = []; $m0.push(parseFloat(json)); alert($m0); //display 750 $m1 ...

Automatically transitioning from a chatbot interface to an Ionic mobile app page as the conversation progresses

My current setup involves incorporating the MS chatbot-framework V3 into my ionic 3 mobile app using Direct line. The goal is to gracefully end the conversation with the chatbot and seamlessly transition to another page within the mobile app, while also p ...

Error message: "Serialization of object to ajax/json cannot be completed

I have encountered an issue while attempting to pass a List MyModel via AJAX/JSON to the controller. I noticed that all the objects are being passed as 'undefined': [Form Post Data] undefined=&undefined=&undefined=&undefined=&un ...

What is the best way to include a RecyclerView row in the WishList feature?

I am looking to incorporate a Wishlist feature similar to Google Play in my app. Each row in my RecyclerView within the QuestionActivity contains a Button (Heart Icon). My goal is for when this heart icon is clicked, the corresponding row in the Recycler ...

The ElasticClient encountered a problem while verifying the connection status

I am currently attempting to verify the status of a connection, but encounter an error during the check. var node = new Uri("http://myhost:9200"); var settings = new ConnectionSettings(node); ElasticClient client = new ElasticClient(settings); ISt ...

Unable to perform JSONArray conversion in Java (Android)

I'm encountering an issue when trying to execute the code below as it keeps throwing an Exception. Code try { JSONObject jsonObject = new JSONObject(result); JSONArray jsonArray = jsonObject.getJSONArray("current"); } catch (JSONExcepti ...

The JSON node fails to return a value after inserting data through an ajax request

I'm encountering an issue with a jQuery plugin that loads JSON data through an AJAX call and inserts it into an existing object. When I attempt to reference the newly inserted nodes, they show up as 'undefined', despite the data appearing co ...

I am having difficulty extracting an image from the JSON data retrieved from the service and displaying it in the recycler view

This is my custom Adapter class where I am facing an issue with parsing images from JSON data retrieved from a service. CustomRecyclerViewAdapter.class public class CustomRecyclerViewAdapter extends RecyclerView.Adapter<CustomRecyclerViewAdapter.ViewH ...

Dealing with the complexities of Jquery Ajax and WCF Webservice integration:

I have developed a WCF Webservice method that accepts two parameters, both strings, and returns an XmlElement. Currently, I am encountering issues with an ASP.NET page that contains a JQuery AJAX call to this method. Despite trying to troubleshoot using o ...

Parsing JSON and presenting it in a recycler-view card fragment

I've been attempting to parse JSON using Volley and display it with a recycler-card view in my tabbed fragment class on Android. However, the JSON response is not being displayed in the fragment. Despite no errors or exceptions showing up, the app run ...