Blob Image unable to covert in to image format? - asp.net-mvc

Unable to retrive the blob image from mysql database using below code in mvc4 with entityframework6
byte[] photo = entity.collections.Where(p => p.CustomerID == CustomerID).Select(img => img.Money_Receipt_Photo).FirstOrDefault();
MemoryStream ms = new MemoryStream(photo);
ms.Write(photo, 0, photo.Length);
System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
System.Drawing.Image returnImage = (Image)converter.ConvertFrom(ms);
return returnImage;
error: ImageConverter cannot convert from System.IO.MemoryStream.

Assuming that you are receiving the stream of bytes from the blob.
Try this code :
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;
}

Related

When upload Bitmap stream to Azure storage, it store zero/empty image

I am using below code to upload a MemoryStream from a bitmap image to my Microsoft azure storage account:
MemoryStream memoryStream = new MemoryStream();
img.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
blob.Properties.ContentType = model.File.ContentType;
blob.UploadFromStream(memoryStream);
What happen by use above code is it uploads an empty image to Azure storage :( !(I found the name but the file size is zero!)!
if (model.File != null && model.File.ContentLength > 0)
{
Bitmap original = null;
var name = "newimagefile";
var errorField = string.Empty;
errorField = "File";
name = Path.GetFileNameWithoutExtension(model.File.FileName);
original = Bitmap.FromStream(model.File.InputStream) as Bitmap;
if (original != null)
{
var img = CreateImage(original, model.X, model.Y, model.Width, model.Height);
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("company"); // must always be lowercase
container.CreateIfNotExists();
container.SetPermissions(
new BlobContainerPermissions
{
PublicAccess =
BlobContainerPublicAccessType.Blob
});
CloudBlockBlob blob = container.GetBlockBlobReference(imgName + ".png");
MemoryStream memoryStream = new MemoryStream();
img.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
blob.Properties.ContentType = model.File.ContentType;
blob.UploadFromStream(memoryStream);
}
Any Help please !
I think you need to set the position back to the start of the stream before uploading
img.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
blob.Properties.ContentType = model.File.ContentType;
memoryStream.Position = 0;
blob.UploadFromStream(memoryStream);

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;
}

convert Emgu image to array and from array to image

I want you to know the methods to get the image from array of bytes :
I'am using this code but it's throw an exception ,if the size is more than 100 or the length of the arary,and if it's less than 50 it save a messay image
Bitmap b = new Bitmap(#"C:/difflena.jpg");
byte[] pixels = lolo(b);
MemoryStream stream = new MemoryStream(pixels, 0, pixels.Length);
Bitmap bitmap = new Bitmap(stream);
Image<Gray, byte> image = new Image<Gray, byte>(60, 60);
image.Bytes = pixels;
image.Save(file + "face" + "t" + ".bmp");
if (image != null) { Label1.Text = "yes";
public byte[] lolo(Bitmap n)
{
/*ImageFormat imageFormat = n.RawFormat;
byte[] Ret=null;
try
{
using (MemoryStream ms = new MemoryStream())
{
n.Save(ms, imageFormat);
Ret = ms.ToArray();
}
}
catch (Exception) { Label1.Text = "no"; }
return Ret;}

How can I open a file in wp7?

I have some files in IsolatedStorage in my application. The file types are different, say doc,xls,ppt,pdf,mp3,mov,jpg,png etc.. I need to open these files. How can I do this.
Try to open it with name and its extensions
byte[] data;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = isf.OpenFile(image.jpg, FileMode.Open, FileAccess.Read))
{
data = new byte[isfs.Length];
isfs.Read(data, 0, data.Length);
isfs.Close();
}
}
MemoryStream ms = new MemoryStream(data);
BitmapImage bi = new BitmapImage();
bi.SetSource(ms);
Image img = new image();
img.source = bi
if it is an image try to set the source of a bitmap image as memory stream ms.

Uploading PostedFile to FTP

I am needing to upload a posted file to an FTP file location in my controller.
Here is what I have now.
public ActionResult Upload(HttpPostedFileBase file)
{
string fileName = System.IO.Path.GetFileName(file.FileName);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://10.10.0.3"+"/"+fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
StreamReader streamReader = new StreamReader(file.InputStream);
byte[] fileContents = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());
streamReader.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
.....
}
The file is being uploaded, it has the correct number of pages, however there is no text in the new file. (these are pdfs, I will do validation on the type later, just trying to get it to work now).
Thanks!
You are reading PDF file as if they were text files. Instead try this.
var sourceStream = file.InputStream;
requestStream = request.GetRequestStream();
request.ContentLength = sourceStream.Length;
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = sourceStream.Read(buffer, 0, BUFFER_SIZE);
do
{
requestStream.Write(buffer, 0, bytesRead);
bytesRead = sourceStream.Read(buffer, 0, BUFFER_SIZE);
} while (bytesRead > 0);
sourceStream.Close();
requestStream.Close();
response = (FtpWebResponse)request.GetResponse();

Resources