OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How to send Base64 Image encoded as JSON from C# client to Python FastAPI server?

  • Thread starter Thread starter zumbide123
  • Start date Start date
Z

zumbide123

Guest
I've managed to merge two codes using FastAPI in Python. The challenge now is sending an image in Base64 format via JSON for interpretation. However, I'm encountering issues, as C# returns System.Net.WebException: 'The remote server returned an error: (500) Internal Server Error'.

Any ideas?

Here are my codes:
Python

Code:
import tensorflow as tf
from fastapi import FastAPI
import json
import base64
from PIL import Image
import io
#from flask import request
from fastapi import Request

app = FastAPI()

# Load the saved model
cnn = tf.keras.models.load_model('modelo_cnn.h5')

# Test functions to verify the connection
# @app.get('/prueba0/')
# def prueba0():
#     return "Hello, I'm connecting..."

# Test function to sum two numbers
@app.get('/prueba1/{a}/{b}')
def prueba1(a: int, b: int):
    return a + b

# Test function to display a message
@app.get('/prueba2/{text}')
def prueba2(text: str):
    return "Hello, your message was... " + text

#########################################################################################

# Overlap identification function
@app.post('/traslape/')
def traslape(request: Request):
    global cnn
    
    # Get data from the request body
    body = request.body()
        
    # Decode JSON data
    data = json.loads(body)
    
    # # # Open the JSON file (image)
    # with open(image) as f:
    #      img = json.load(f)
    
    # # Decode the image
    # image = base64.b64decode(img["image"])
    
    # # Open the image from bytes using Pillow
    # image = Image.open(io.BytesIO(image))
    
    # # Concatenate images horizontally
    # #imagen_completa = tf.concat([imagen_i, imagen_d], axis=1)
    
    # # Apply gamma correction to the image
    # gamma = tf.convert_to_tensor(0.6)
    # gamma_corrected = tf.pow(imagen / 255.0, gamma) * 255.0 # imagen_completa
    # image_bw = tf.cast(gamma_corrected, tf.uint8)
    
    # # Convert the image to grayscale
    # grayscale_image = tf.image.rgb_to_grayscale(image_bw)
    
    # # Define new dimensions
    # new_height = 360
    # new_width = 500

    # # Resize the image
    # imagen_completa_resize = tf.image.resize(grayscale_image, [new_height, new_width])
      
    # # Perform classification using the loaded model
    # result = cnn.predict(imagen_completa_resize)
     
    # if result[0][0] > result[0][1]:
    #     result = False # No mask
    # else:
    #     result = True # With mask

    return True

c#​


Code:
using System;
using System.IO;
using System.Net;
using System.Text;

namespace comunica_api
{
    class Program
    {
        static void Main(string[] args)
        {
            // Path to the image in your local file system
            string imagePath = @"C:\Users\VirtualImages[00]20240418_124751_028.jpg";

            try
            {
                // Read the bytes of the image from the file
                byte[] imageBytes = File.ReadAllBytes(imagePath);

                // Convert the bytes to a Base64 formatted string
                string base64String = Convert.ToBase64String(imageBytes);

                // URL of the API
                string url = "http://localhost:8000/traslape/";

                // Data to send
                string json = "{\"image\": \"" + base64String + "\"}";

                // Create the HTTP request
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST"; // Use the POST method 
                request.ContentType = "application/json"; // Set content type as JSON
                request.ContentLength = json.Length;

                // Convert JSON string to bytes
                byte[] jsonBytes = Encoding.UTF8.GetBytes(json);

                // Print the request content before sending it
                Console.WriteLine("Request:");
                Console.WriteLine("URL: " + url);
                Console.WriteLine("Method: " + request.Method);
                Console.WriteLine("Headers:");
                foreach (var header in request.Headers)
                {
                    Console.WriteLine(header.ToString());
                }
                Console.WriteLine("Body:");
                Console.WriteLine(json);


                // Write bytes into the request body using StreamWriter
                using (Stream requestStream = request.GetRequestStream())
                using (StreamWriter writer = new StreamWriter(requestStream))
                {
                    // Write JSON string into the request body
                    writer.Write(json);
                }

                // Send the request and get the response
                
                // HERE IS THE ERROR
                using (var response = (HttpWebResponse)request.GetResponse()) 
                //
                
                {
                    // Read the response from the server
                    using (var streamReader = new StreamReader(response.GetResponseStream()))
                    {
                        // Read the response as a string and display it in the console
                        string responseText = streamReader.ReadToEnd();
                        Console.WriteLine("API Response:");
                        Console.WriteLine(responseText);
                    }
                }
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("The specified image could not be found.");
            }
            catch (WebException ex)
            {
                // Handle any communication error with the API
                Console.WriteLine("API Communication Error:");
                Console.WriteLine(ex.Message);
            }

            // Wait for the user to press Enter before exiting the program
            Console.ReadLine();
        }
    }
}
<p>I've managed to merge two codes using FastAPI in Python. The challenge now is sending an image in Base64 format via JSON for interpretation. However, I'm encountering issues, as C# returns <code>System.Net.WebException: 'The remote server returned an error: (500) Internal Server Error'</code>.</p>
<p>Any ideas?</p>
<p>Here are my codes:<br />
<strong>Python</strong></p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
from fastapi import FastAPI
import json
import base64
from PIL import Image
import io
#from flask import request
from fastapi import Request

app = FastAPI()

# Load the saved model
cnn = tf.keras.models.load_model('modelo_cnn.h5')

# Test functions to verify the connection
# @app.get('/prueba0/')
# def prueba0():
# return "Hello, I'm connecting..."

# Test function to sum two numbers
@app.get('/prueba1/{a}/{b}')
def prueba1(a: int, b: int):
return a + b

# Test function to display a message
@app.get('/prueba2/{text}')
def prueba2(text: str):
return "Hello, your message was... " + text

#########################################################################################

# Overlap identification function
@app.post('/traslape/')
def traslape(request: Request):
global cnn

# Get data from the request body
body = request.body()

# Decode JSON data
data = json.loads(body)

# # # Open the JSON file (image)
# with open(image) as f:
# img = json.load(f)

# # Decode the image
# image = base64.b64decode(img["image"])

# # Open the image from bytes using Pillow
# image = Image.open(io.BytesIO(image))

# # Concatenate images horizontally
# #imagen_completa = tf.concat([imagen_i, imagen_d], axis=1)

# # Apply gamma correction to the image
# gamma = tf.convert_to_tensor(0.6)
# gamma_corrected = tf.pow(imagen / 255.0, gamma) * 255.0 # imagen_completa
# image_bw = tf.cast(gamma_corrected, tf.uint8)

# # Convert the image to grayscale
# grayscale_image = tf.image.rgb_to_grayscale(image_bw)

# # Define new dimensions
# new_height = 360
# new_width = 500

# # Resize the image
# imagen_completa_resize = tf.image.resize(grayscale_image, [new_height, new_width])

# # Perform classification using the loaded model
# result = cnn.predict(imagen_completa_resize)

# if result[0][0] > result[0][1]:
# result = False # No mask
# else:
# result = True # With mask

return True
</code></pre>
<h2>c#</h2>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.IO;
using System.Net;
using System.Text;

namespace comunica_api
{
class Program
{
static void Main(string[] args)
{
// Path to the image in your local file system
string imagePath = @"C:\Users\VirtualImages[00]20240418_124751_028.jpg";

try
{
// Read the bytes of the image from the file
byte[] imageBytes = File.ReadAllBytes(imagePath);

// Convert the bytes to a Base64 formatted string
string base64String = Convert.ToBase64String(imageBytes);

// URL of the API
string url = "http://localhost:8000/traslape/";

// Data to send
string json = "{\"image\": \"" + base64String + "\"}";

// Create the HTTP request
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST"; // Use the POST method
request.ContentType = "application/json"; // Set content type as JSON
request.ContentLength = json.Length;

// Convert JSON string to bytes
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);

// Print the request content before sending it
Console.WriteLine("Request:");
Console.WriteLine("URL: " + url);
Console.WriteLine("Method: " + request.Method);
Console.WriteLine("Headers:");
foreach (var header in request.Headers)
{
Console.WriteLine(header.ToString());
}
Console.WriteLine("Body:");
Console.WriteLine(json);


// Write bytes into the request body using StreamWriter
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream))
{
// Write JSON string into the request body
writer.Write(json);
}

// Send the request and get the response

// HERE IS THE ERROR
using (var response = (HttpWebResponse)request.GetResponse())
//

{
// Read the response from the server
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
// Read the response as a string and display it in the console
string responseText = streamReader.ReadToEnd();
Console.WriteLine("API Response:");
Console.WriteLine(responseText);
}
}
}
catch (FileNotFoundException)
{
Console.WriteLine("The specified image could not be found.");
}
catch (WebException ex)
{
// Handle any communication error with the API
Console.WriteLine("API Communication Error:");
Console.WriteLine(ex.Message);
}

// Wait for the user to press Enter before exiting the program
Console.ReadLine();
}
}
}
</code></pre>
 

Latest posts

Top