1

I have a c# application which have a bitmap object. I wish to call a python script and send him the bitmap. The idea is to not save the bitmap on the hard drive because it will slow down the application. I wish to use the memory of the application directly.

Do you have an idea how I can do this ?

Thank you :)

2
  • Do you know already how to pass a single byte? An array of bytes? Commented May 28, 2020 at 7:26
  • While saving it to the hard drive might "slow it down", you run the risk of corrupting the image (e.g. encoding loss) if passing it through as data in the arguments. There's also a limit on how large arguments can be, so there would be a limit to the size of files you can deal with. That might be OK for your use case if the images you're dealing with are small and simple, but it's something to consider. Commented May 28, 2020 at 7:50

2 Answers 2

3

The solution based on the idea of tdelaney. I use the standard input / output to communicate.

C#

        Bitmap bitmap = new Bitmap(@"test.jpg");

        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = @"c:\Python30\python.exe";
        p.StartInfo.Arguments = string.Format("{0} {1}", "test.py", "");
        p.StartInfo.RedirectStandardInput = true;
        p.Start();

        using (var memoryStream = new MemoryStream())
        {
            bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            var bytes = memoryStream.ToArray();
            memoryStream.Seek(0, SeekOrigin.Begin);
            p.StandardInput.BaseStream.Write(bytes, 0, bytes.Length);
            p.StandardInput.BaseStream.Flush();
            p.StandardInput.BaseStream.Close();
        }

        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();

Python :

import sys
import msvcrt
import os

msvcrt.setmode (sys.stdin.fileno(), os.O_BINARY)
bitmap = sys.stdin.buffer.read()

output = open("/tmp/testpython.jpg","wb")
output.write(bitmap)
output.close()

print("hehe")

exit(0)
Sign up to request clarification or add additional context in comments.

Comments

2

Write the python program to read the bitmap from stdin

import sys
bitmap = sys.stdin.read()

Have the C# program execute the program with stdin set to a pipe, write the bitmap and then close the pipe.

1 Comment

Excellent idea !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.