In my silvelright application, I have an image that is stored in a byte[]. I want to save the image to Azure Blobl Storage using REST services, but it only accepts Strings (UploadStringTaskAsync)
I have tried many ways to convert my byte[] to a valid String but without success :
Encoding.UTF8.GetString(data, 0, data.Length)
Encoding.Unicode.GetString(data, 0, data.Length)
Even with a custom function (at least that function gives me the right String length)
var sb = new StringBuilder();
foreach(byte b in data)
sb.Append((char)b);
return sb.ToString();
But the image is always corrupted and/or unreadable on the other side. What am I doing wrong?
Thanks
Use Convert.FromToBase64String method on client. Then decode it on server with Convert.FromBase64String.
Update:
You can also use WebClient.OpenWriteAsync method.
Related
I have a table column with string data beginning with 0xFFD8FFE000.... and ending with FFD9. Each row is similar in start and end, but different between.
If I inspect the resulting HTML around the image, I learn that it displays as a PNG. My end goal is a scripted export that will convert the string to a file. I am looking for info, links included, to send me on my way.
You have a few options. All of them include some amount of coding. There isn't a built in way for SQL Server to export base64 encoded strings as files.
However you can....
Write a CLR that will do it from the TSQL / database side. The relevant C# code you would need in the CLR is something like this:
File.WriteAllBytes(#"c:\yourfile", Convert.FromBase64String(yourBase64String));
This is courtesy of this link: Base64 encoded string to file
Or write a quick console application to run through each of your rows and pull it out. Using the same code snippet above for C# or any other number of languages that are documented out on google. Another method a quick google search found is:
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
Courtesy of here: http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx
As stated, how should we properly save a captured signature using SignaturePad component to a SQL Server database? Well it should be easy, considering the GetImage(false) method used by the component returns a Bitmap and later on compress the Bitmap into a JPEG and into an array byte using a Stream. The byte array should then be saved directly to the SQL Server database; however, the problem with this approach is that when you retrieve the image from the database, the image is all black. It's like the strokes were never captured, funny thing though is that the background color of the SignaturePad was set to White and the stroke color is Black.
Xamarin.Android Button OnClick Event Handler
var signature = this.SignatureView.GetImage(false); // This returns the Bitmap from SignaturePad.
var imageData = this.ImageToByteArray(signature); // This converts the Bitmap to byte[].
var result = this.SaveDataAsync(imageData); // Save the byte[] to the database.
Xamarin.Android Extension Method
private byte[] ImageToByteArray(Bitmap image)
{
if (image == null) return null;
byte[] result;
using (var stream = new MemoryStream())
{
image.Compress(CompressFormat.Jpeg, 100, stream);
result = stream.ToArray();
stream.Flush();
}
return result;
}
This is the same approach we did on iOS, but doesn't work on Android. Any ideas or working solution would be very much appreciated.
Thanks!
Copied from Xamarin Forum - Components Section
Okay, I think I found a solution to this issue, which was described in this thread Signature Pad for Xamarin.Forms. I am not sure why we need to specify the colors within the GetImage() method, while the properties for the Stroke and Background colors has already been specified. Well, I guess the colors needed to draw the image is not the same with that of the properties.
I am using Restlet framework. I create one web service that returns a file to the client.
On the server side, I first create a FileRepresentation object, instantiate it correctly, and return it to the client as Representation.
On the client side, I want to extract the content of the Representation, how can I cast the Representation object to FileRepresentation?
Thanks in advance!!
In fact, the FileRepresentation class is provided in order to fill request / response from a file but can't be used to extract content of a response.
To have access to your response content on the client side, it depends on the file type. If you receive an ascii content, you can do something like that:
Representation representation = resource.get();
String fileContent = representation.getText();
If it's a binary file, you need to work with a stream, as described below:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
resource.get().write(outputStream);
byte[] fileContent = outputStream.toByteArray();
Hope it helps you,
Thierry
I'm working with a ComponentOne (C1) silverlight PDF viewer control.
It has a "LoadDocument" method that accepts a "Stream".
I'm making an HTTP get call from my client app to get a PDF document.
This document, on the server side, has been streamed in through File.ReadAllBytes(), then converted to a base64 string using Convert.ToBase64String().
This string is sent across the wire back to my silverlight app where it's then reversely converted back into a byte array with Convert.FromBase64String(val).
Then I'm creating a MemoryStream with that byte array and passing "LoadDocument()" that memory stream.
The viewer is rendering nothing. It shows the toolbar and scrollbars, but the contents are blank and the save button is grayed out, suggesting that no document loaded.
I know for certain the file made it across because the byte array size on the client matches teh byte array pre-conversion on the server side.
Here's my code: (in the interest of time/space, i've truncated, removing validation, etc.)
SERVERSIDE
string sendingToClient = Convert.ToBase64String(File.ReadAllBytes(filePath))
CLIENTSIDE
byte[] image = null;
image = Convert.FromBase64String(stringFromServerCall);
MemoryStream stream = new MemoryStream(image);
docViewer.LoadDocument(stream);
edit As a potential workaround, I attempted to save the file into isolated storage with a ".pdf" extension. Then I use the IsolatedStorageFileStream to send to LoadDocument().
I've come to an actual error, it now says "PdfParserException was unhandled by user code: invalid file format (missing pdf header)"
Can anyone shed some light on this PDF header?
Here is an experiment I would conduct.
Add a button to your Xaml and on click use OpenFileDialog to get a FileInfo. From that FileInfo use its Open method to get a stream and pass that to docViewer.LoadDocument.
Now run it, click the button and select the same PDF document you are trying to send from the server.
If that succeeds you need to continue investigating your server streaming strategy. On the other hand if you still have the same problem, well it doesn't get more raw than that. Try other PDF files and start investigating the PDF component. Have you ever actually used it successfully, if so how does this current usage differ.
you should get the stream pointer back to 0 ,so this should do the trick
byte[] image = null;
image = Convert.FromBase64String(stringFromServerCall);
MemoryStream stream = new MemoryStream(image);
stream.Position = 0;
docViewer.LoadDocument(stream);
What i'm trying to do is transfer an image from the web service to the mobile client. In order to do this i've created a web service operation that returns a byte[] variable. In this method i create an .png image from a chart. After this i get the bytes from the image and provide them as a return value for the operation. this is the server code:
public byte[] getBytes() throws IOException {
BufferedImage chartImage = chart.createBufferedImage(230, 260);
//I get the image from a chart component.
ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
ImageIO.write( chartImage, "png",baos );
baos.flush();
byte[] bytesImage = baos.toByteArray();
baos.close();
return bytesImage;
}
Now in the mobile application all i do is assign a byte[] variable the return value of the web service operation.
byte[] imageBytes = Stub.getBytes().
Maybe i'm missing something but this is not working as i get this runtime error:
java.rmi.MarshalException: Expected Byte, received: iVBORw0KGgoAAAANSUhEU.... (very long line).
have any ideas why this happends? Or maybe you can suggest any other way to send the data to the mobile client.
If the service is only delivering an image as a byte array, the overhead induces by wrapping this in a SOAP response and XML/SOAP parsing on the client side seem rather unnecessary. Why don't you implement the chart generation in a servlet and let the client retrieve the image from a 'non-SOAP' server URL?
Instead of returning bytesImage from a WebService method like you do, you could instead write the byte array to the servlet's response object:
response.setContentType("image/png");
response.setContentLength(bytesImage.length);
OutputStream os = response.getOutputStream();
os.write(bytesImage);
os.close();
On the J2ME client, you would read the response from the URL, to which the servlet is bound and create an image from the data:
HttpConnection conn = (HttpConnection)Connector.open("http://<servlet-url>");
DataInputStream dis = conn.openDataInputStream();
byte[] buffer = new byte[conn.getLength()];
dis.readFully(buffer);
Image image = Image.createImage(buffer, 0, buffer.length);
Hope this helps!