I use Asp.Net Core 3.0 and I need to convert TIFF string to png/jpg image in run time and display it but I phased this problem
ArgumentException: Parameter is not valid. System.Drawing.Image.FromStream(Stream stream, bool useEmbeddedColorManagement, bool validateImageData)
First: What I did,
- I read the TIFF string from XML File as shown in the below code
[HttpGet]
public async Task<IActionResult> ReadData()
{
XmlDocument document = new XmlDocument();
document.Load(@"Location In the Computer\MyFile.xml");
XmlNodeList sign = document.GetElementsByTagName("sign");
byte[] buffer = Encoding.ASCII.GetBytes(sign.Item(0).InnerText);
ViewBag.Sign = ConvertTiffToImage(buffer); //This method convert tiff to png/jpg
return View("Create");
}
I used ConvertTiffToImage method to convert tiff string to png/jpg image as shown in the below code
private string ConvertTiffToImage(byte[] tiffBytes) { //Read the tiff and convert to png MemoryStream ms = new MemoryStream(tiffBytes); MemoryStream newMS = new MemoryStream(); Bitmap.FromStream(ms).Save(newMS, ImageFormat.Png); //Error come here //Read the converted memorystream and insert it to string to display StreamReader reader = new StreamReader(newMS); string pngImage = reader.ReadToEnd(); return pngImage; }
I tried to display the Image using ViewBag as shown in the below code
@if (ViewBag.Sign == null)
{
<img src="~/Images/NoSignature.png" class="rounded" alt="No Signature Found for Emirates Id" />
}
else
{
<img src="data:image/png;base64,@ViewBag.Sign" class="rounded" alt="Signature in Emirates Id" />
}
- I debugged my application and the error raised in this point
Bitmap.FromStream(ms).Save(newMS, ImageFormat.Png);
, The displayed error isArgumentException: Parameter is not valid. System.Drawing.Image.FromStream(Stream stream, bool useEmbeddedColorManagement, bool validateImageData)
Second: What I need to do is reading tiff string from XML file and display the image (png/jpg) using Viewbag in the run time.
This is the XML file data: <sign>SUkqAJYAAAA7VR0Dy7B2GGDhhgwcMMG4YYMOGG2RrhwwwQcNtgiQ7ww2gT23CCeG2wl30F224QX4SCVvUIL6CQVvSBBfCQStpBIIL4QQS4QhBBQQhBBTs0BCPoKdrYUx4QUERaUggUERh8JQQLwlQJJJBUC4hUtLSSVKK6C6XQXQXC9LgttLhEJJXaCulbgsQrCgAgAgEQAAAQMAAQAAABwBAAABAQMAAQAAADAAAAACAQMAAQAAAAEAAAADAQMAAQAAAAQAAAAGAQMAAQAAAAAAAAAKAQMAAQAAAAEAAAANAQIAAQAAAAAAAAARAQQAAQAAAAgAAAASAQMAAQAAAAEAAAAVAQMAAQAAAAEAAAAWAQMAAQAAADAAAAAXAQQAAQAAAI4AAAAaAQUAAQAAAGgBAAAbAQUAAQAAAHABAAAcAQMAAQAAAAEAAAAoAQMAAQAAAAIAAAAxAQIAOQAAAHgBAAAAAAAAAACAJQAAIAAAAIAlAAAgAEltYWdlTWFnaWNrIDUuNS43IDA1LzIzLzAzIFE4IGh0dHA6Ly93d3cuaW1hZ2VtYWdpY2sub3JnAA==</sign>
Third: This is some resources that I search:
1. Converting TIFF files to PNG in .Net
2. Converting string to byte array in C#
3. ASP.NET Core MVC, Get file from database, and render as image
How to convert tiff to png/jpg and display it in the application run time in Asp.Net Core 3.0?