Hi so I'm trying to save an image selected by the user to file so that i can later upload it to my mySQL database.
So I have this code:
var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
{
Title = "Please pick a selfie"
});
var stream = await result.OpenReadAsync();
resultImage.Source = ImageSource.FromStream(() => stream);
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "myfile");
using (var streamWriter = new StreamWriter(filename, true))
{
streamWriter.WriteLine(GetImageBytes(stream).ToString());
}
using (var streamReader = new StreamReader(filename))
{
string content = streamReader.ReadToEnd();
System.Diagnostics.Debug.WriteLine(content);
}
Here's the GetImageBytes(..) function:
private byte[] GetImageBytes(Stream stream)
{
byte[] ImageBytes;
using (var memoryStream = new System.IO.MemoryStream())
{
stream.CopyTo(memoryStream);
ImageBytes = memoryStream.ToArray();
}
return ImageBytes;
}
The code kind of works, it creates a file but doesn't save the image. Instead it saves "System.Bytes[]". It saves the name of the object, not the contents of the object.
myfile
enter image description here
Any help would be really appreciated. Thanks!
StreamWriter is for writing formatted strings, not binary data. Try this instead
File.WriteAllBytes(filename,GetImageBytes(stream));
Encode the byte array as a base64 string, then store that in the file:
private string GetImageBytesAsBase64String(Stream stream)
{
var imageBytes;
using (var memoryStream = new System.IO.MemoryStream())
{
stream.CopyTo(memoryStream);
imageBytes = memoryStream.ToArray();
}
return Convert.ToBase64String(imageBytes);
}
If you later need to retrieve the image bytes from the file, you can use the corresponding Convert.FromBase64String(imageBytesAsBase64String) method.
Related
I am working on ASP.Net MVC 4.7 project, in which I am using Microsoft graph api to send mail.
I want to know what is the contentByte. How I can get it from the filestream. See the following code. I am searching for
fileAttachment.ContentBytes=
Note that files are in stream they are uploaded by the user.
private static MessageAttachmentsCollectionPage GetAttachments(List<HttpPostedFileBase> fileUploader)
{
var attachmentPage = new MessageAttachmentsCollectionPage();
if (fileUploader != null)
{
foreach (var file in fileUploader)
{
var fileAttachment = new FileAttachment();
fileAttachment.Name = file.FileName;
fileAttachment.ContentType = file.ContentType;
fileAttachment.ContentBytes = ??
attachmentPage.Add(fileAttachment);
}
}
This is just a base64-encoded contents of the file (string). For example:
public static class StreamExtensions
{
public static string ConvertToBase64(this Stream stream)
{
if (stream is MemoryStream memoryStream)
{
return Convert.ToBase64String(memoryStream.ToArray());
}
var bytes = new Byte[(int)stream.Length];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(bytes, 0, (int)stream.Length);
return Convert.ToBase64String(bytes);
}
}
You may find different approaches described in the Encode a FileStream to base64 with c# thread.
I have a variable which holds a pdf stream , this variable is of type System.Threading.Tasks.Task<Stream>. I want to save this pdf stream in a pdf file but I am not sure how to do so . Below is a piece of code I tried to work on . Any ideas as to what I can try to save this stream in a file
System.Threading.Tasks.Task<Stream> pdf = //Some logic here which gets a pdf stream
I want to store the pdf content in the variable in a file as a pdf
For that I worote the method
public static void SaveStreamAsFile(string filePath, System.Threading.Tasks.Task<Stream> inputStream, string fileName)
{
string path = Path.Combine(filePath, fileName);
using (FileStream outputFileStream = new FileStream(path, FileMode.Create))
{
// logic
}
}
Read the input stream and write it to the output stream..
public static async Task SaveStreamAsFile(string filePath, System.Threading.Tasks.Task<Stream> inputStream, string fileName)
{
var stream = await inputStream;
var path = Path.Combine(filePath, fileName);
var bytesInStream = new byte[stream.Length];
await stream.ReadAsync(bytesInStream, 0, (int) bytesInStream.Length);
using (var outputFileStream = new FileStream(path, FileMode.Create))
{
await outputFileStream.WriteAsync(bytesInStream, 0, bytesInStream.Length);
}
}
I'm using Magick.NET to convert a PDF to a PNG and stream it back to the page via ajax.
Everything works until a PDF is uploaded twice. When trying to overwrite or delete the existing file, the debugger tells me that the file is in use by another process.
Here's my function that returns an Image to the controller:
//path is a fully qualified path to a file ending in .PDF
private Image ConvertPDFTOneImage(string path)
{
MagickReadSettings settings = new MagickReadSettings();
settings.Density = new PointD(300, 300);
using (MagickImageCollection images = new MagickImageCollection())
{
FileInfo file = new FileInfo(path);
images.Read(file);
file = null;
using (MagickImage horizontal = images.AppendHorizontally())
{
string PNGName = Path.ChangeExtension(path, ".png");
horizontal.Write(PNGName);
}
return Image.FromFile(path.Replace("pdf", "png"));
}
}
And my controller that streams the response back to the browser:
public async Task<HttpResponseMessage> PostFormData([FromUri] int sellerID, [FromUri] int eventID, [FromUri] string section, [FromUri] string row, [FromUri] string seat)
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
try
{
string base64 = string.Empty;
SellerObjects.Externeal.SellerTicket TicketToSave = new SellerObjects.Externeal.SellerTicket();
TicketToSave.UploadedFile = HttpContext.Current.Request.Files["UploadedImage"];
SellerTicketRepo TheLocalSellerRepo = new SellerTicketRepo(TicketToSave);
using (MemoryStream ms = new MemoryStream())
{
TheLocalSellerRepo.GetConvertedPDFImage().Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
base64 = System.Convert.ToBase64String(ms.ToArray());
}
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StringContent(base64);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, "Error saving file.");
}
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "An error has occurred");
}
I am assuming that the Image class that you are returning is a System.Drawing.Image. You need to Dispose this object to release the file lock.
// Instead of this:
using (MemoryStream ms = new MemoryStream())
{
TheLocalSellerRepo.GetConvertedPDFImage().Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
base64 = System.Convert.ToBase64String(ms.ToArray());
}
// Should you be doing this:
using (MemoryStream ms = new MemoryStream())
{
using (Image img = TheLocalSellerRepo.GetConvertedPDFImage())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
base64 = System.Convert.ToBase64String(ms.ToArray());
}
}
// Or you could even do this (if GetConvertedPDFImage() returns a MagickImage):
using (MagickImage img = TheLocalSellerRepo.GetConvertedPDFImage())
{
img.Format = MagickFormat.Jpeg;
base64 = img.ToBase64();
}
I have met an issue regarding the casting type from HttpInputStream to FileStream.
How I did ?
I have a HttpPostedFileBase object and I want to have FileStream.
I wrote:
public void Test(HttpPostedFileBase postedFile) {
FileStream fileStream = (FileStream)(postedFile.InputStream); // throw exception
FileStream anotherFileStream = postedFile.InputStream as FileStream; // null
}
I tried also
public void Test(HttpPostedFileBase postedFile) {
Stream stream = postedFile.InputStream as Stream;
FileStream myFile = (FileStream)stream;
}
But no success.
Why at postedFile.InputStream comes HttpInputStream type ?
And how could I solve this issue ?
Thanks
public byte[] LoadUploadedFile(HttpPostedFileBase uploadedFile)
{
var buf = new byte[uploadedFile.InputStream.Length];
uploadedFile.InputStream.Read(buf, 0, (int)uploadedFile.InputStream.Length);
return buf;
}
The stream that you get from your HTTP call is read-only sequential (non-seekable) and the FileStream is read/write seekable. You will need first to read the entire stream from the HTTP call into a byte array, then create the FileStream from that array.
I used the following and it worked just fine for the same situation
MemoryStream streamIWant = new MemoryStream();
using (Stream mystream = (Stream)AmazonS3Service.GetObjectStream(AWSAlbumBucketName, ObjectId))
{
mystream.CopyTo(streamIWant);
}
return streamIWant;
The GetObjectStream returns the same type of string mentioned in the question.
You can use the .SaveAs method to save the file content. HttpInputSteam probably because it's uploaded through http [browser]
postedFile.SaveAs("Full Path to file name");
You can also use CopyTo
FileStream f = new FileStream(fullPath, FileMode.CreateNew);
postedFile.InputStream.CopyTo(f);
f.Close();
Below code worked for me..
Use a BinaryReader object to return a byte array from the stream like:
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
How to create byte array from HttpPostedFile
It will work for you.
IFormFile file;
if (file != null)
{
byte[]? image = Array.Empty<byte>();
await using var memoryStream = new MemoryStream();
await file!.CopyToAsync(memoryStream);
image = memoryStream.ToArray();
}
First convert to byte array then convert to Stream.
[HttpPost]
[Route("api/TestReader/UploadTestReaderStudentsGrade")]
public IHttpActionResult UploadTestReaderStudentsGrade()
{
HttpPostedFile httpPostedFile = HttpContext.Current.Request.Files[0];
var fileBytes = new byte[httpPostedFile.InputStream.Length];
httpPostedFile.InputStream.Read(fileBytes, 0, (int)httpPostedFile.InputStream.Length); // to byte array
Stream stream = new MemoryStream(fileBytes); // to Stream
Workbook workbook = new Workbook(stream);
return Ok();
}
Here is my code:
protected void SaveMyImage_Click(object sender, EventArgs e)
{
string imageUrl = Hidden1.Value;
string saveLocation = Server.MapPath("~/PictureUploads/whatever2.png") ;
HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
WebResponse imageResponse = imageRequest.GetResponse();
Stream responseStream = imageResponse.GetResponseStream();
using (BinaryReader br = new BinaryReader(responseStream))
{
imageBytes = br.ReadBytes(500000);
br.Close();
}
responseStream.Close();
imageResponse.Close();
FileStream fs = new FileStream(saveLocation, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(imageBytes);
}
finally
{
fs.Close();
bw.Close();
}
}
}
The top imageUrl declartion is taking in a Base64 image string, and I want to convert it into an image. I think my set of code only works for images like "www.mysite.com/test.jpg" not for a Base64 string. Anybody have some suggestions? Thanks!
Here is an example, you can modify the method to accept a string parameter. Then just save the image object with image.Save(...).
public Image LoadImage()
{
//data:image/gif;base64,
//this image is a single pixel (black)
byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
It is possible to get an exception A generic error occurred in GDI+. when the bytes represent a bitmap. If this is happening save the image before disposing the memory stream (while still inside the using statement).
You can save Base64 directly into file:
string filePath = "MyImage.jpg";
File.WriteAllBytes(filePath, Convert.FromBase64String(base64imageString));
Here is what I ended up going with.
private void SaveByteArrayAsImage(string fullOutputPath, string base64String)
{
byte[] bytes = Convert.FromBase64String(base64String);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
image.Save(fullOutputPath, System.Drawing.Imaging.ImageFormat.Png);
}
I would suggest via Bitmap:
public void SaveImage(string base64)
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
{
using (Bitmap bm2 = new Bitmap(ms))
{
bm2.Save("SavingPath" + "ImageName.jpg");
}
}
}
Here is working code for converting an image from a base64 string to an Image object and storing it in a folder with unique file name:
public void SaveImage()
{
string strm = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
//this is a simple white background image
var myfilename= string.Format(#"{0}", Guid.NewGuid());
//Generate unique filename
string filepath= "~/UserImages/" + myfilename+ ".jpeg";
var bytess = Convert.FromBase64String(strm);
using (var imageFile = new FileStream(filepath, FileMode.Create))
{
imageFile.Write(bytess, 0, bytess.Length);
imageFile.Flush();
}
}
In my case it works only with two line of code. Test the below C# code:
String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";
byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);
That's it. Kindly up vote if you really find this solution works for you. Thanks in advance.
In a similar scenario what worked for me was the following:
byte[] bytes = Convert.FromBase64String(Base64String);
ImageTagId.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);
ImageTagId is the ID of the ASP image tag.
If you have a string of binary data which is Base64 encoded, you should be able to do the following:
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
You should be able to write the resulting array to a file.
public bool SaveBase64(string Dir, string FileName, string FileType, string Base64ImageString)
{
try
{
string folder = System.Web.HttpContext.Current.Server.MapPath("~/") + Dir;
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
string filePath = folder + "/" + FileName + "." + FileType;
File.WriteAllBytes(filePath, Convert.FromBase64String(Base64ImageString));
return true;
}
catch
{
return false;
}
}
Using MemoryStream is not a good idea and violates a specification in MSDN for Image.FromStream(), where it says
You must keep the stream open for the lifetime of the Image.
A better solution is using ImageConverter, e.g:
public Image ConvertBase64ToImage(string base64)
=> (Bitmap)new ImageConverter().ConvertFrom(Convert.FromBase64String(base64));
In NetCore 6.0, you can use HttpClient and the async methods in the new File class.
The implementation is very simple:
static async Task DownloadFile(string imageUrl, string pathToSave)
{
var content = await GetUrlContent(url);
if (content != null)
{
await File.WriteAllBytesAsync(pathToSave, content);
}
}
static async Task<byte[]?> GetUrlContent(string url)
{
using (var client = new HttpClient())
using (var result = await client.GetAsync(url))
return result.IsSuccessStatusCode ? await result.Content.ReadAsByteArrayAsync():null;
}
Usage:
await DownloadFile("https://example.com/image.jpg", #"c:\temp\image.jpg");