How-to: Byte array of an image to string, send back through HTTP request, then back to byte[] image? - asp.net-mvc

I have a byte array of an image on the server.
Using MVC as a pseudo-REST web service interface.
I'm in need of sending this image back through the HTTP request to the MVC client to render.
My first attempt was using UFT8Encoding to encode it to a string, send that cross then decode it using UTF8Encoding on the client.
However, when I do this, the result on the client is null. I assume due to the format of the string that I'm trying to send back.
This is what I'm doing now to no avail:
byte[] image = GetBarcodeImage(barcode);
if (image != null)
{
UTF8Encoding enc = new UTF8Encoding();
result = enc.GetString(image);
}
This is on the client side:
UTF8Encoding encoding= new UTF8Encoding();
byte[] image = encoding.GetBytes(result);
string imageBase64 = Convert.ToBase64String(image);
string imgsrc = string.Format("data:image/gif;base64,{0}", imageBase64);

Is there any reason you don't return it as an image from your controller?
var image = GetByteArrayImage();
var stream = new MemoryStream(image);
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Expires = 14400;
return File(stream, "image/jpg");
Thin in your client you can just use WebRequest to download the file like any other file and not have to do any other magic.

Related

How to get Image Name or Id from docx file using Open xml in C#?

I am using Mvc.Net API with open XML. I need to replace multiple images in .docx file.I replace the images in current scenario but I don't get any Id or Name of the Image at my code side so facing difficulties to replace those images.
Here is my code
List<ImagePart> imgPartList = doc.MainDocumentPart.ImageParts.ToList();
foreach(ImagePart imgPart in imgPartList)
{
string Id=doc.MainDocumentPart.GetIdOfPart(imgPart);
byte[] imageBytes = File.ReadAllBytes(ImagePath);
BinaryWriter writer = new BinaryWriter(imgPart.GetStream());
writer.Write(imageBytes);
writer.Close();
}
Can I get the name of Image in ImagePart?
I would do something like this:
List<ImagePart> imgPartList = doc.MainDocumentPart.ImageParts.ToList();
foreach(ImagePart imgPart in imgPartList)
{
var imageId = document.MainDocumentPart.GetIdOfPart(imgPart.Id);
byte[] imageBytes = File.ReadAllBytes(ImagePath);
BinaryWriter writer = new BinaryWriter(imgPart.GetStream());
writer.Write(imageBytes);
writer.Close();
}
Also
This answer could help you

Make picture from base64 on client-side

How to make a picture from a base64-string to send it to server by using HttpRequest.request?
For example, I have the following base64-string:
'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
Instead of sending it I would like to post a jpeg to server? Is it possible?
Convert Base64 to bytes
How to native convert string -> base64 and base64 -> string
Upload binary as image
Dart how to upload image
EDIT
(this is the server part, I have to look for the client part)
Client code:
var request = new HttpRequest()
..open("POST", 'http://yourdomain.com/yourservice')
..overrideMimeType("image/your-imagetype") // might be that this doesn't work than use the next line
..setRequestHeader("Content-Type", "image/your-imagetype")
..onProgress.listen((e) => ...);
request
..onReadyStateChange.listen((e) => ...)
..onLoad.listen((e) => ...)
..send(yourBinaryDataAsUint8List);
Convert to image:
I think you need to create a dataURL like show here How to upload a file in Dart?
and then use the created dataUrl as src in code like shown here How to load an image in Dart
see also Base64 png data to html5 canvas as #DanFromGermany mentioned in his comment on the question.
It may be necessary to convert List to Uint8List in between.
Please add a comment if you need more information.
I like decoding on server-side, but anyways.
Basically you just split a text you got from canvas.toDataUrl(), convert the Base64 text to binary data, then send it to server. Use "CryptoUtils" in "crypto" library to treat Base64. I haven't tested with any proper http server, but this code should work.
// Draw an on-memory image.
final CanvasElement canvas = document.createElement('canvas');
canvas.width = 256;
canvas.height = 256;
final CanvasRenderingContext2D context = canvas.getContext('2d');
final CanvasGradient gradient = context.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(0, "#1e4877");
gradient.addColorStop(0.5, "#4584b4");
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(10, 10);
context.lineTo(240, 240);
context.lineWidth = 10;
context.strokeStyle = '#ff0000';
context.stroke();
// Convert the image to data url
final String dataUrl = canvas.toDataUrl('image/jpeg');
final String base64Text = dataUrl.split(',')[1];
final Uint8ClampedList base64Data = new Uint8ClampedList.fromList(
CryptoUtils.base64StringToBytes(base64Text));
// Now send the base64 encoded data to the server.
final HttpRequest request = new HttpRequest();
request
..open("POST", 'http://yourdomain.com/postservice')
..onReadyStateChange.listen((_) {
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print("onReadyStateChange: " + request.responseText); // output the response from the server
}
})
..onError.listen((_) {
print("onError: " + _.toString());
})
..send(base64Data);
I posted a complete snippet here. https://gist.github.com/hyamamoto/9391477
I found the Blob conversion part not to be working (anymore?).
The code from here does work:
Blob createImageBlob(String dataUri) {
String byteString = window.atob(dataUri.split(',')[1]);
String mimeString = dataUri.split(',')[0].split(':')[1].split(';')[0];
Uint8List arrayBuffer = new Uint8List(byteString.length);
Uint8List dataArray = new Uint8List.view(arrayBuffer.buffer);
for (var i = 0; i < byteString.length; i++) {
dataArray[i] = byteString.codeUnitAt(i);
}
Blob blob = new Blob([arrayBuffer], mimeString);
return blob;
}

Failed to upload a local image file onto google doc with format converted

For public link it works fine, but in my case I need upload a image file from local disk. I converted the image into base64 format, and write the html file into local disk as well, that html file can be opened in browser with image showing, but the document in google doc just an empty file, even I drag that html file into google docs the image still not there. My code is below:
DocsService client = new DocsService("testappv3");
client.setUserCredentials("username", "password");
File file = new File("c:/test.bmp");
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
int read;
byte[] buff = new byte[1024];
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
out.flush();
String base64 = Base64.encode(out.toByteArray());
String mimeType = DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();
String html = "<html><body><img src=\"data:" + mimeType + ";base64," + base64 + "\"/></body></html>";
URL destFolderUrl = new URL("https://docs.google.com/feeds/default/private/full/<FOLDER_ID>/contents");
DocumentEntry newDocument = new DocumentEntry();
newDocument.setTitle(new PlainTextConstruct("test"));
newDocument.setMediaSource(new MediaByteArraySource(html.getBytes(), "text/html"));
newDocument = client.insert(destFolderUrl, newDocument);
Look my experience level is only a few years so I could well be wrong but .... My understanding is that you can no longer use
client.insert(destFolderUrl, newDocument);// but now must use ResumableGDataFileUploader
new ResumableGDataFileUploader.Builder(client, new URL(uploadLink), mediaFile, null )
hopefully someone with more knowledge will confirm or deny

Could not upload a local image file embedded into HTML as a data URI into google doc via java api

I need upload a image file from local disk. I converted the image into base64 format, and write the html file into local disk as well, that html file can be opened in browser with image showing, but the document in google doc just an empty file, even I drag that html file into google docs the image still not there. My code is below:
DocsService client = new DocsService("testappv3");
client.setUserCredentials("username", "password");
File file = new File("c:/test.bmp");
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
int read;
byte[] buff = new byte[1024];
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
out.flush();
String base64 = Base64.encode(out.toByteArray());
String mimeType = DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();
String html = "<html><body><img src=\"data:" + mimeType + ";base64," + base64 + "\"/></body></html>";
URL destFolderUrl = new URL("https://docs.google.com/feeds/default/private/full/<FOLDER_ID>/contents");
DocumentEntry newDocument = new DocumentEntry();
newDocument.setTitle(new PlainTextConstruct("test"));
newDocument.setMediaSource(new MediaByteArraySource(html.getBytes(), "text/html"));
newDocument = client.insert(destFolderUrl, newDocument);
This looks like a bug, we are trying to fix it, and I will get back to you when we have a fix.
Thanks for your patience.

Blackberry MD5 authentication with HTTP Post

I need to send to a server in POST an email (String) and a password (MD5 hash in byte[]).
Below how I get my MD5 hash where "password" is a String (what the user enter):
byte[] passMD5 = Crypto.encodeStringMD5(password);
And the function:
public static byte[] encodeStringMD5(String s) throws Exception {
byte[] bytes = s.getBytes();
MD5Digest digest = new MD5Digest();
digest.update(bytes, 0, bytes.length);
int length = digest.getDigestLength();
byte[] md5 = new byte[length];
digest.getDigest(md5, 0, true);
return md5;
}
So "passMD5" should be an MD5 hash in bytes of my string value "password", right?
Then I need to send the information through HTTP POST to an URL and read the result (XML). See below the rest of the code:
readURL(urlTemplate, email, passMD5);
Where urlTemplate is a String like "http://www.domain.com/myfile.aspx?action=login&enc=1", email a String and password the MD5 hash in bytes.
The readURL below:
private void readURL(String url, String email, byte[] pass) throws IOException {
HttpConnection conn = null;
InputStream in = null;
OutputStream os = null;
byte dataBytes[];
try {
URLEncodedPostData data = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
data.append("email", email);
data.append("pass", pass.toString());
dataBytes = data.getBytes();
conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", data.getContentType());
conn.setRequestProperty("Content-Length", Integer.toString(dataBytes.length));
os = conn.openOutputStream();
os.write(dataBytes);
os.flush();
os.close();
in = conn.openInputStream();
verifyLogin(getLoginContent(in));
} catch (IOException e) {
} catch (IllegalArgumentException e) {
} finally {
ConnectionUtil.close(conn, in);
ConnectionUtil.close(conn, os);
}
}
So right now the MD hash of the password in transformed to a String in order to be added to the data.append() function that only takes String parameters...
I think because of this, I don't send the good MD5 hash and it makes a problem.
On the server side in ASP.NET C#, I have this:
byte[] PasswordHash;
if (enc == 0) {
MD5 MD5Hasher = MD5.Create();
PasswordHash = MD5Hasher.ComputeHash(Encoding.Unicode.GetBytes(Password));
} else {
PasswordHash = Encoding.Unicode.GetBytes(Password);
}
So when I ask this URL "http://www.domain.com/myfile.aspx?action=login&enc=0" and give the password AS IS (so a String, not a byte[] and not MD5 hash) and do
data.append("pass", password);
then it works.
I just have either a problem with creating my MD5 hash or with the HTTP POST or both...
Please help me!
You can't just call "toString()" on a byte[] and expect to get a meaningful result. If you want to convert it to a hex representation of the bytes, you need a method to do that. I suggest going back to your previous question at Blackberry encode MD5 different from MD5 in C# since you had a function there that did the converstion from byte[] to String.

Resources