i have problem with png HTML renderer,
i am trying to send png of View to email, but on email i get 0B .png
PS: Ticket.pdf is ok
using (MemoryStream ms = new MemoryStream())
{
var pdf = PdfGenerator.GeneratePdf(RenderRazorViewToString("TicketTemplateBig", model), PdfSharp.PageSize.A4);
pdf.Save(ms, false);
/////////////////
//Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (MemoryStream ms2 = new MemoryStream())
{
//Image image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(RenderRazorViewToString("TicketTemplateBig", model));
Bitmap bitmap = (Bitmap)Image.FromFile(#"C:\logo.png");
bitmap.Save(ms2, ImageFormat.Png);
/////////////////
await ms.FlushAsync();
await ms2.FlushAsync();
mm.Attachments.Add(new Attachment(ms, string.Format("Ticket.pdf"), "application/pdf"));
streams.Add(ms);
mm.Attachments.Add(new Attachment(ms2, string.Format("logo.png"), "application/png"));
streams.Add(ms2);
await client.SendMailAsync(mm);
}
}
You are trying to send the mail before having effectively written to ms2.
you need to do flush the ms2 stream buffer before adding it to mm . (as you did for ms, that's why the pdf part was handled correctly)
(Also, minor typo : "application/png" instead of "application/Png", probably not an issue)
problem : stream was on last position
result : ms2.Position = 0;
using (MemoryStream ms = new MemoryStream())
{
var pdf = PdfGenerator.GeneratePdf(RenderRazorViewToString("TicketTemplateBig", model), PdfSharp.PageSize.A4);
pdf.Save(ms, false);
using (MemoryStream ms2 = new MemoryStream())
{
Image image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(RenderRazorViewToString("TicketTemplateBig", model));
image.Save(ms2, ImageFormat.Png);
ms2.Position = 0;
await ms.FlushAsync();
await ms2.FlushAsync();
mm.Attachments.Add(new Attachment(ms, string.Format("Ticket.pdf"), "application/pdf"));
mm.Attachments.Add(new Attachment(ms2, string.Format("Ticket.png"), "application/png"));
await client.SendMailAsync(mm);
}
}
Thanks Guys
Related
I have an Image I am retrieving from the database as a byte array. I want to save it outside the Project i.e on the Clients System. I would appreciate if the code aspect can be assisted with. Here is a sample method I have so far:
public Image byteArrayToImage2()
{
var filePath = "C:\\cat.jpg";
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
Image returnImage = null;
using (MemoryStream ms = new MemoryStream(fileBytes))
{
returnImage = Image.FromStream(ms);
returnImage.Save("cat2.jpg", ImageFormat.Jpeg);
}
return returnImage;
}
Try the below approach
PS: make sure your fileBytes is of type byte Array.
MemoryStream imageStream = new MemoryStream();
imageStream.Write(fileBytes, 0, fileBytes.Length);
// Include the file name along with extension (Eg: 'C:\TestImage.JPEG')
FileStream fs = File.Create("Give the path where you want to save the image");
imageStream.WriteTo(fs);
fs.Close();
imageStream.Close();
I have two functions: one to convert from image to byte and other to convert from byte to bitmapImage.
So, when I open the window with that images, I convert from byte to bitmapImage and it works great, but when I close and open it again it just keeps on memory and if I continue to do that time and time again it just throws an exception Out Of Memory exception
Image to byte->
private byte[] ConvertImageToBinary(Image img)
{
using (MemoryStream ss = new MemoryStream())
{
img.Save(ss, System.Drawing.Imaging.ImageFormat.Jpeg);
var s = ss.ToArray();
var jpegQuality = 50;
Image image;
using (var inputStream = new MemoryStream(s))
{
image = Image.FromStream(inputStream);
var jpegEncoder = System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders()
.First(c => c.FormatID == System.Drawing.Imaging.ImageFormat.Jpeg.Guid);
var encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, jpegQuality);
Byte[] outputBytes;
using (var outputStream = new MemoryStream())
{
image.Save(outputStream, jpegEncoder, encoderParameters);
return outputBytes = outputStream.ToArray();
}
}
}
}
Byte to bitmap ->
public BitmapImage ConvertBinaryToImage(byte[] array)
{
var image = new BitmapImage();
using (var ms = new MemoryStream(array))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad; // here
image.StreamSource = ms;
image.EndInit();
image.Freeze();
}
return image;
}
When I open the WindowDragAndDrop it loads all the images
But when I close it it still uses the same amount of memory
Image is indeed disposable (https://learn.microsoft.com/en-us/dotnet/api/system.drawing.image?view=netframework-4.8), so you also need:
using (var image = Image.FromStream(inputStream)){
}
Around everywhere you use Image objects.
The last line of the following code gives the error "Parameter is not valid", when the original image is an SVG:
var imageBytes = Convert.FromBase64String(imageBase64String);
var memStream = new MemoryStream(imageBytes);
//memStream.Seek(0, SeekOrigin.Begin);
var imageObject = new Bitmap(memStream);
Help please. Thanks.
EDIT: The image for example I am using is the image of the first formula in the following page right under the Theoremsection:
https://en.wikipedia.org/wiki/Green%27s_theorem
Can you try with 'using' for memorystream to handle garbage collection by itself?
var imageBytes = Convert.FromBase64String(imageBase64String);
Bitmap m = ByteToBitmap(imageBytes);
public static Bitmap ByteToBitmap(byte[] imageByte)
{
using (MemoryStream mStream = new MemoryStream())
{
mStream.Write(imageByte, 0, imageByte.Length); // this will stream dataand handle image length by itself
mStream.Seek(0, SeekOrigin.Begin);
Bitmap bm = new Bitmap(mStream);
return bm;
}
}
For SVG,
public static Bitmap ByteToBitmap(byte[] imageByte)
{
using (MemoryStream mStream = new MemoryStream(imageByte))
{
var s= SvgDocument.Open(mStream);
var bm= svgDocument.Draw();
return bm;
}
}
I created a web service in .Net Core. This service return an image png with pixel format 8pp indexed :
using (Bitmap bmp = new Bitmap(img.width, img.height, PixelFormat.Format8bppIndexed))
{
using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, imgFormat);
return new FileContentResult(ms.ToArray(), $"image/png");
}
}
I want to test this service, so I created a C# test with this piece of code :
Task<HttpResponseMessage> responseTask = client.PostAsync(url, content);
responseTask.Wait();
var response = responseTask.Result;
HttpContent ct = response.Content;
byte[] data = await ct.ReadAsByteArrayAsync();
using (MemoryStream m = new MemoryStream(data))
{
Bitmap img = new Bitmap(m);
img.Save(filePath, ImageFormat.Png);
}
But the Bitmap img is Format32bppArgb. How can I do to get my image in original format (Format8bppIndexed) ?
Just save straighway what you got:
using (var fs = new FileStream(filePath, FileMode.Create))
fs.Write(data, 0, data.Length);
Hi i'm making an aplication that takes a picture from a car and its driver and this pictures are send to a web service, i am having problems for dealing with this situation, right now i've tried to send an encoded 64 base string, but this is not working
EDIT
Here is the code that i'm using for take the picture and save it as a byte array
ImageEncodingProperties format = ImageEncodingProperties.CreateJpeg();
//rotate and save the image
using (var imageStream = new InMemoryRandomAccessStream())
{
//generate stream from MediaCapture
await PhotoCapture.CapturePhotoToStreamAsync(format, imageStream);
await PhotoCapture.StopPreviewAsync();
//create decoder and encoder
BitmapDecoder dec = await BitmapDecoder.CreateAsync(imageStream);
BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(imageStream, dec);
//roate the image
enc.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees;
//write changes to the image stream
await enc.FlushAsync();
PreviewImage = new WriteableBitmap(350, 500);
PreviewImage.SetSource(imageStream);
}
CaptureElement.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
using (var ms = PreviewImage.PixelBuffer.AsStream())
{
MemoryStream memoryStream = new MemoryStream();
ms.CopyTo(memoryStream);
DriverModel.Picture = memoryStream.ToArray();
}
When i'm doing this the array size is like 28 millions, obviusly i'm making something wrong