I developed a C# web application that calls a web-service which returns a base64 encoded array (PDF file). I then convert that array into a UCOMIStream object (I know it is obsolete, but the DLL that I am using requires it as a parameter). I use the following code to do the conversion which works perfectly. I can pass this object to the DLL so that I can print the PDF.
This works great on the Webserver, but the requirement is to print it locally.
Byte[] bBuffer = statementOut.statementcycle.statementdata.content;
int size = bBuffer.Length;
IntPtr mem = Marshal.AllocHGlobal(size);
Marshal.Copy(bBuffer, 0, mem, size);
// Create an OLE Stream object.
System.Runtime.InteropServices.UCOMIStream str; //obsolete but the createstreamonhglobal outputs it
CreateStreamOnHGlobal(mem, true, out str);
The DLL resides on the client so I am able to use ActiveX to create the object using javascript and/or VBscript;however, I have not been able to figure out how to get the stream object to the client to pass to the DLL.
How can this be achieved?
Couldn't you just generate the pdf on the server and have the client download it?
Have the client download that base64 encoded array and then translate the data into a UCOMIStream object and generate the PDF the client side.
Related
I am working on a project that uses a web service developed in Java. The response of this web service is a json file with a key generated with this java method (Base64.getEncoder().encode(array), where "array" is byte[]. This key is supposedly a binary to generate the pdf, but as much as I try, the pdf is not generated correctly, it cannot be opened.
Can anybody help me to generate a pdf with this response in C#?
You need to convert from Base64, to byte and then get the pdf:
Check this example:
string base64EncodedFile = // Get the string representation from the api
using (System.IO.FileStream stream = System.IO.File.Create("c:\\saved.pdf))
{
System.Byte[] byteArray = System.Convert.FromBase64String(base64EncodedFile);
stream.Write(byteArray, 0, byteArray.Length);
}
For more information check wikipedia on base 64
Base64 is a way to encode binary data into an ASCII character set
known to pretty much every computer system, in order to transmit the
data without loss or modification of the contents itself
And that is why the java service does the conversion.
I need to take a Pillow image and either convert it to a byte array or pack it somehow to send it over a ZeroMQ socket. Since the other socket connection isn't in python (it's c#), I can't use pickle, and I'm not sure JSON would work since it's just the image (dimensions sent separately). I'm working with an image created from a processed numpy array out of opencv, so I don't have an image file. Sending the numpy array over didn't work, either.
Since I can't read the image bytes from a file, I've tried Image.getdata() and Image.tobytes() but I'm not sure either were in the right form to send over the socket. What I really need is a bytestream that I can reform into an array after crossing the socket.
UPDATE: So now I'm specifically looking for anything easily undone in C#. I've looked into struct.pack but I'm not sure there's an equivalent to unpack it. Turning the image into an encoded string would work as long as I could decode it.
UPDATE 2: I'm thinking that I could use JSON to send a multidimensional array, then grab the JSON on the other side and turn it into a bitmap to display. I'm using clrzmq for the C# side, though, and I'm not sure how that handles JSON objects.
In case anyone was wondering, here's what I ended up doing:
On the python side:
_, buffer = cv2.imencode('.jpg', cFrame )
jpg_enc = base64.b64encode(buffer).decode('utf-8')
self.frameSender.send_string(jpg_enc)
self.frameSender.send_string(str(height))
self.frameSender.send_string(str(width))
On the C# side:
byte[] bytebuffer = Convert.FromBase64String(frameListener.ReceiveFrame().ReadString());
int height = int.Parse(frameListener.ReceiveFrame().ReadString());
int width = int.Parse(frameListener.ReceiveFrame().ReadString());
using (MemoryStream ms = new MemoryStream(bytebuffer)) //image data
{
Bitmap img = new Bitmap(Image.FromStream(ms), new Size(height, width));
pictureboxVideo.BeginInvoke((MethodInvoker)delegate{pictureboxbVideo.Image = img;});
}
Is there anything open source available for this?
or
Is there a way to parse a stream of bytes received from a POST request manually and convert the chunks of bytes to the appropriate data types?
I'm not sure if there is anything open source for this, but PHP does support the needed features out of the box.
the contents of a POST request can be retrieved as follows:
$data = file_get_contents("php://input");
// or to handle the data as a stream
$stream = fopen("php://input", "rb");
The above is the preferred method, as $HTTP_RAW_POST_DATA is deprecated.
The data can then be parsed using the PHP unpack() function.
I am developing an Android App using Xamarin Studio in order to capture a picture and then send it to a web service.
The steps are:
Capture the picture and store it on the phone.
The web service receives an object as argument. This object contains the image in Base64. This is achieved in the following line:
oImagenFace.ImagenDocumento =(string)Base64ToBitmapDrawableConverter.ConvertBack(BitmapFactory.DecodeFile (imagepath));
At this point I am getting an Out of Memory Exception, but I can not resize the image (as explained here http://developer.android.com/training/displaying-bitmaps/load-bitmap.html) because I need it with the original size. The images are about 200Kb.
Did you tried to skip the BitmapFactory.DecodeFile, and convert the whole file into Base64?
Sg. like this:
oImagenFace.ImagenDocumento =(string)Base64ToBitmapDrawableConverter.ConvertBack(imagepath);
If that won't help, I would try to read the file by chunks and convert that parts to Base64.
Upload Image on Web Server using Android / C# {Xamarin}
This is Just Small Piece of Code. it can send any image from Android to your Web
Server.
System.Net.WebClient Client = new System.Net.WebClient();
Client.Headers.Add("Content-Type", "binary/octet-stream");
byte[] result = Client.UploadFile("localhost/FolderName/upload.php", "POST", path);
string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
Here is the PHP Code {upload.php}. Create a Folder name { Uploads } in
your Application.
<?php
$uploads_dir = 'uploads/'; //Directory to save the file that comes from client application.
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
?>
Java Code:
public class EMessage implements Serializable
{
private Bitmap image;
private String type;
EMessage()
{}
}
...
EMessage eMessage=new EMessage();
outToServer = new DataOutputStream(clientSocket.getOutputStream());
objectOutputStream=new ObjectOutputStream(outToServer);
objectOutputStream.writeObject(eMessage);
C# Code:
[Serializable]
class EMessage
{
private Bitmap image;
private String type;
EMessage()
{ }
}
client = server.AcceptTcpClient();
Connected = client.Connected;
ns = client.GetStream();
IFormatter formatter = new
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
EMessage recievedmsg = (EMessage)formatter.Deserialize(ns);
When I send an object from Android Client App (java coded) and I recieve the object in C# Server App but with an Exception.
"The Input Stream is not a valid binary format. The Starting Content(in bytes) are:
00-05-73-72-00-1D-63-6F-6D-2E etc";
Please suggest any simple solution. My project isn't that much complex. I just need to send an EMessage object.
Serialization formats are specific to the platforms, and Java and .NET serialization aren't compatible with each other. Use JSON instead (and it's easier to debug as well).
Why not use SOAP, here's an article on exactly what you're doing (android to .net)
http://www.codeproject.com/Articles/29305/Consuming-NET-Web-Services-via-the-kSOAP-library
I suggest you drop the Serialization for the above mentioned reasons (Java serialization being different from C# serialization), and transfer your data between your Java and C# applications in plain byte arrays.
You can convert your Bitmap image to a byte array like so (taken from this post on SO):
Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Of course you could change the CompressFormat if circumstances so require. After that, you could convert your type string to a byte array too, and add a null-terminator to the end of it.
Once you're there, you can send your type string first, and add the byte array of the bitmap after it. On the C# end, you could read the incoming data until you reach the 0 terminator, at which point you'll know you've read the string portion of your EMessage object, and then read the rest of the bytes you've sent over and parse them into a Bitmap object.
That way you'll be sure that between your Java and C# implementations, you won't run into any compatibility issues. It may require a bit more code and a little more understanding to do, but it's far more reliable than serializing between two languages.