POST image from webcam in Silverlight window to MVC Controller - asp.net-mvc

I have an MVC 4 application with a button for taking a photo that opens up a new window with javascript which contains a silverlight application in it. The silverlight application can then take a photo using the webcam and store it as a Writeable Bitmap. What I would like to do is then push that bitmap onto an action in my controller for saving to the database and refreshing the view.
I know I need to send the image as a post to my controller, but any code examples or suggestions on how I would go about doing that would be greatly appreciated. I think it should work as follows, Button Click for saving the image in my silverlight application would call a POST to the MVC controller and attach the image stream as a parameter in the controller, and the controller can then take the stream and push it up to the database then I can close the silverlight window. Just not sure how to go about coding that.

You could send the image using a WebClient. Let's suppose that you have the image inside your Silverlight application in a byte array:
byte[] image = ... get the image from your webcam
var client = new WebClient();
var uri = new Uri("http://example.com/photos/upload");
client.OpenWriteCompleted += (sender, e) =>
{
var buffer = (byte[])e.UserState;
e.Result.Write(buffer, 0, buffer.Length);
e.Result.Close();
};
client.OpenWriteAsync(uri, "POST", image);
and on the MVC side:
[HttpPost]
public ActionResult Upload()
{
byte[] image = new byte[Request.InputStream.Length];
Request.InputStream.Read(image, 0, image.Length);
// TODO: do something with the uploaded image here ...
}

Thank you for the reply. This is exactly what I was looking for, however ive run into a problem. Silverlight gives me the webcam snapshot as a WriteableBitmap type. Which I then tried to convert to a byte[] array before sending it over to MVC. It is saving to the database successfully, however it does not appear to be a valid image when I try to pull it back out from the database and display it. Is there an issue that you can see with my conversion code? Or perhaps can I send it over as an image type, or can I only send over byte[] arrays through http posts like this?
In my Silverlight application:
private void SendImage()
{
var client = new WebClient();
var uri = new Uri("http://localhost:4600/GuestBadge/GetCameraImage");
client.OpenWriteCompleted += (sender, e) =>
{
var buffer = (byte[])e.UserState;
e.Result.Write(buffer, 0, buffer.Length);
e.Result.Close();
};
client.OpenWriteAsync(uri, "POST", ToByteArray(SnapShot));
}
public static byte[] ToByteArray(WriteableBitmap bmp)
{
// Init buffer
int w = bmp.PixelWidth;
int h = bmp.PixelHeight;
int[] p = bmp.Pixels;
int len = p.Length;
byte[] result = new byte[4 * w * h];
// Copy pixels to buffer
for (int i = 0, j = 0; i < len; i++, j += 4)
{
int color = p[i];
result[j + 0] = (byte)(color >> 24); // A
result[j + 1] = (byte)(color >> 16); // R
result[j + 2] = (byte)(color >> 8); // G
result[j + 3] = (byte)(color); // B
}
return result;
}
And in my controller:
[HttpPost]
public ActionResult GetCameraImage()
{
byte[] image = new byte[Request.InputStream.Length];
Request.InputStream.Read(image, 0, image.Length);
var getPerson = (from a in db.Persons where a.PersonID == 3 select a).FirstOrDefault();
getPerson.Picture = image;
db.SaveChanges();
return null;
}

I ended up using FJCore http://code.google.com/p/fjcore/ to encode my WriteableBitmap into JPEG and then converted that to BASE64 using code I found at this question Using FJCore to encode Silverlight WriteableBitmap THANKS!. Then in turn converted that out to a byte[] array and sent it to MVC using your code and now its working great. I'm pretty new at all this stuff and didn't quite understand the encoding process enough before. Below is the code I used for this. Thanks again for your help!
private static string GetBase64Jpg(WriteableBitmap bitmap)
{
int width = bitmap.PixelWidth;
int height = bitmap.PixelHeight;
int bands = 3;
byte[][,] raster = new byte[bands][,];
for (int i = 0; i < bands; i++)
{
raster[i] = new byte[width, height];
}
for (int row = 0; row < height; row++)
{
for (int column = 0; column < width; column++)
{
int pixel = bitmap.Pixels[width * row + column];
raster[0][column, row] = (byte)(pixel >> 16);
raster[1][column, row] = (byte)(pixel >> 8);
raster[2][column, row] = (byte)pixel;
}
}
ColorModel model = new ColorModel { colorspace = ColorSpace.RGB };
FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(model, raster);
MemoryStream stream = new MemoryStream();
JpegEncoder encoder = new JpegEncoder(img, 90, stream);
encoder.Encode();
stream.Seek(0, SeekOrigin.Begin);
byte[] binaryData = new Byte[stream.Length];
long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);
string base64String =
System.Convert.ToBase64String(binaryData,
0,
binaryData.Length);
return base64String;
}
private void SendImage()
{
var client = new WebClient();
var uri = new Uri("http://localhost:4600/GuestBadge/GetCameraImage");
client.OpenWriteCompleted += (sender, e) =>
{
var buffer = (byte[])e.UserState;
e.Result.Write(buffer, 0, buffer.Length);
e.Result.Close();
};
client.OpenWriteAsync(uri, "POST", Convert.FromBase64String(GetBase64Jpg(SnapShot)));
}

Related

How to get the total page number in iText7 when adding that info to the document footer?

In iTextSharp, we can override the OnCloseDocument() event and add the Page # of #total on the footer of the document. However, the PdfDocument does not have this document close event anymore. Since we cannot determine the total number of pages while adding new pages, how can we determine this total number and put it on the footer while generating the document?
I've seen some suggestions with brute force method: after the PDF document is generated and before it's flushed, use PdfReader to read through it to get the total number before updating the footer. Is this the only way? Is there any better way of doing this?
Thanks.
That is one of the ways of doing it.
Another way of doing that is described in this code sample:
protected void manipulatePdf(String dest) throws Exception {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
Document doc = new Document(pdfDoc);
int numberOfPages = pdfDoc.getNumberOfPages();
for (int i = 1; i <= numberOfPages; i++) {
// Write aligned text to the specified by parameters point
doc.showTextAligned(new Paragraph(String.format("page %s of %s", i, numberOfPages)),
559, 806, i, TextAlignment.RIGHT, VerticalAlignment.TOP, 0);
}
doc.close();
}
In that code sample you would add the footer after creating and flushing the PDF. This is a very simple and easy way of doing this request.
Another way of doing that is with IEventHandler.
PdfWriter writer = new PdfWriter(myMemoryStream);
pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new TextFooterEventHandler(document));
then :
public class TextFooterEventHandler : IEventHandler
{
protected Document doc;
public TextFooterEventHandler(Document doc)
{
this.doc = doc;
}
public void HandleEvent(Event currentEvent)
{
var docEvent = (PdfDocumentEvent)currentEvent;
var pageSize = docEvent.GetPage().GetPageSize();
var fonts = new FontHelper();
var font = fonts.Label();
int pageNum = docEvent.GetDocument().GetPageNumber(docEvent.GetPage());
float coordX = ((pageSize.GetLeft() + doc.GetLeftMargin())
+ (pageSize.GetRight() - doc.GetRightMargin())) / 2;
float footerY = doc.GetBottomMargin();
Canvas canvas = new Canvas(docEvent.GetPage(), pageSize);
canvas
.SetFont(font)
.SetFontSize(8)
.ShowTextAligned((("Page " + pageNum.ToString())), coordX + 250, footerY - 40, TextAlignment.CENTER)
.SetLineThrough()
.Close();
}
}

How to print bitmap without zoom from MVC controller in Debian

Document is printed from MVC controller to Debian Squeeze Linux server printer using code below in Mono.
Page in printer is A4.
Printed text in paper is too big and unsharp. Rightmost part of text is not visible since it does not fit to page.
If printed from Windows from .NET to HP Laserjet, output is correct.
So it looks like Mono or Samsung ML-331x Series printer zooms bitmap for unknown reason which causes too big and unsharp output.
How to fix this so that bitmap is printed like in windows ?
Possible solutions:
Best way would be to print formatted html directly. How to do it in server where there are no browser installed? wkhtmltopdf does not support printing. I posted it in How to print formatted html in Linux server
Maybe it is possible to use wkhtmltopdf convert html to pdf instead of bitmap I posted it as separate question in How to print pdf in debian linux from MVC controller
wkhtmltoimage can produce also other image formats. Maybe some other format is better ?
Maybe some wkhtmltoimage command line swithches like --width=750 or --dpi can fix this ?
public class Test: Controller
{
public ActionResult Print()
{
PrintOrderVormiga();
return new ContentResult() { Content = "OK" };
}
void PrintOrderVormiga()
{
StringBuilder sb = new StringBuilder();
sb.Insert(0, " test ", 500);
var bmp = ConvertHtmlToBMP("<html><body>" +sb.Tostring()+ "</body></html>");
var doc = new PrintDocument();
doc.PrinterSettings.PrinterName = "Samsung ML-331x Series";
doc.PrintPage += new PrintPageEventHandler(ProvideContent);
pageHeight = doc.DefaultPageSettings.PaperSize.Height;
using (bm = new Bitmap(new MemoryStream(bmp)))
{
lehti = (int)Math.Ceiling(bm.Height / (double)pageHeight);
doc.PrinterSettings.FromPage = 1;
doc.PrinterSettings.ToPage = lehti;
pageno = 0;
doc.Print();
}
}
int pageno, lehti;
int pageHeight;
Bitmap bm;
void ProvideContent(object sender, PrintPageEventArgs e)
{
Rectangle cropRect = new Rectangle(0, pageHeight * pageno++,
bm.Width, pageHeight);
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
e.Graphics.DrawImage(bm, new Rectangle(0, 0, target.Width, target.Height),
cropRect,
GraphicsUnit.Pixel);
e.HasMorePages = pageno < lehti;
}
static byte[] ConvertHtmlToBMP(string html)
{
string programm = "wkhtmltoimage";
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
programm = "wkhtmltoimage-amd64";
}
var p = new Process
{
StartInfo =
{
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
UseShellExecute = false,
FileName = Environment.OSVersion.Platform == PlatformID.Win32NT ?
"C:\\Program Files\\wkhtmltopdf\\bin\\" + programm + ".exe" : "/usr/bin/" + programm
}
};
p.StartInfo.Arguments = "--format bmp --disable-javascript --quality 10";
p.StartInfo.Arguments += " - -";
p.Start();
using (var stream = p.StandardInput)
{
byte[] ibuffer = System.Text.Encoding.UTF8.GetBytes(html);
stream.BaseStream.Write(ibuffer, 0, ibuffer.Length);
stream.WriteLine();
}
var buffer = new byte[32768];
byte[] file;
using (var ms = new MemoryStream())
{
while (true)
{
var read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
break;
}
ms.Write(buffer, 0, read);
}
file = ms.ToArray();
}
p.WaitForExit(60000);
var returnCode = p.ExitCode;
p.Close();
return file;
}
}
You can use this HTML to PDF Converter for Mono solution from EvoPdf. The C# code for converting a HTML to PDF in Mono is:
// create the HTML to PDF converter object
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIPAddress, serverPortNumber);
// set service password if necessary
if (serverPassword.Length > 0)
htmlToPdfConverter.ServicePassword = serverPassword;
// set PDF page size
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
// set PDF page orientation
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
// convert the HTML page from given URL to PDF in a buffer
byte[] pdfBytes = htmlToPdfConverter.ConvertUrl(urlToConvert);

Generate torrent links from server-side

I don't know a lot about torrents, at least not enough to understand how certain websites can offer both a normal download link and a torrent link to download a file uploaded by a user.
Is generating a torrent link something common and simple to achieve. Would I need a server installation?
I've made an ugly C# implementation from a Java source, and to make sure some of my encoded variables were correct, I used NBEncode from Lars Warholm.
// There are 'args' because I'm using it from command-line. (arg0 is an option not used here)
// Source file
args[1] = Directory.GetCurrentDirectory() + args[1];
// Name to give to the torrent file
args[2] = Directory.GetCurrentDirectory() + args[2];
var inFileStream = new FileStream(args[1], FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var filename = args[2];
//BEncoding with NBEencode
var transform = new BObjectTransform();
MemoryStream s = new MemoryStream();
OSS.NBEncode.Entities.BDictionary bod = new OSS.NBEncode.Entities.BDictionary();
OSS.NBEncode.Entities.BDictionary meta = new OSS.NBEncode.Entities.BDictionary();
// Preparing the first part of the file by creating BEncoded objects
string announceURL = "https://www.mysite.com/announce";
int pieceLength = 512 * 1024;
bod.Value.Add(new BByteString("name"), new OSS.NBEncode.Entities.BByteString(filename));
bod.Value.Add(new BByteString("length"), new OSS.NBEncode.Entities.BInteger(inFileStream.Length));
bod.Value.Add(new BByteString("piece length"), new OSS.NBEncode.Entities.BInteger(pieceLength));
bod.Value.Add(new BByteString("pieces"), new BByteString(""));
meta.Value.Add(new BByteString("announce"), new BByteString(announceURL));
meta.Value.Add(new BByteString("info"), bod);
byte[] pieces = hashPieces(args[1], pieceLength);
transform.EncodeObject(meta, s);
s.Close();
// Notice that we finish with a dictionary entry of "pieces" with an empty string.
byte[] trs = s.ToArray();
s.Close();
inFileStream.Close();
// I don't know how to write array of bytes using NBEncode library, so let's continue manually
// All data has been written a MemoryStreamp, except the byte array with the hash info about each parts of the file
Stream st = new FileStream(filename + ".torrent", FileMode.Create);
BinaryWriter bw = new BinaryWriter(st);
// Let's write these Bencoded variables to the torrent file:
// The -4 is there to skip the current end of the file created by NBEncode
for (int i = 0; i < trs.Length - 4; i++)
{
bw.BaseStream.WriteByte(trs[i]);
}
// We'll add the length of the pieces SHA1 hashes:
var bt = stringToBytes(pieces.Length.ToString() + ":");
// Then we'll close the Bencoded dictionary with 'ee'
var bu = stringToBytes("ee");
// Let's append this to the end of the file.
foreach (byte b in bt)
{
bw.BaseStream.WriteByte(b);
}
foreach (byte b in pieces)
{
bw.BaseStream.WriteByte(b);
}
foreach (byte b in bu)
{
bw.BaseStream.WriteByte(b);
}
bw.Close();
st.Close();
// That's it.
}
Functions used:
private static byte[] stringToBytes(String str)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] bytes = encoding.GetBytes(str);
return bytes;
}
private static byte[] hashPieces(string file, int pieceLength)
{
SHA1 sha1 = new SHA1CryptoServiceProvider();
StreamReader inn = new StreamReader(file);
MemoryStream pieces = new MemoryStream();
byte[] bytes = new byte[pieceLength];
byte[] digest = new byte[20];
int pieceByteCount = 0, readCount = inn.BaseStream.Read(bytes, 0, pieceLength);
while (readCount != 0)
{
pieceByteCount += readCount;
digest = sha1.ComputeHash(bytes, 0, readCount);
if (pieceByteCount == pieceLength)
{
pieceByteCount = 0;
foreach (byte b in digest)
{
pieces.WriteByte(b);
}
}
readCount = inn.BaseStream.Read(bytes, 0, pieceLength - pieceByteCount);
}
inn.Close();
if (pieceByteCount > 0)
foreach (byte b in digest)
{
pieces.WriteByte(b);
}
return pieces.ToArray();
}
It depends on how you're trying to create it. If you run a website, and want to generate torrent files from uploaded files, then you'll obviously need server-side code.
Generating a torrent file involves: adding the files you want to the torrent, and adding tracker info. Some popular trackers are:
http://open.tracker.thepiratebay.org/announce
http://www.torrent-downloads.to:2710/announce
To create the .torrent file, you'll have to read the about the format of the file. A piece of Java that generates .torrent files is given at https://stackoverflow.com/a/2033298/384155

How do I get an in-memory chart (or image) into an in-memory OpenXML document?

I'm having a nightmare of a time trying to add a Chart to a MemoryStream in-memory.
I'm creating a Word document on the fly using OpenXML and I have a chart that is also being dynamically generated from data in the database.
I get the template from the database as a byte array, passing that into a method that also takes a business object that holds a bunch of data to populate bookmarks held within that template.
Here's the method:
public Stream Parse(byte[] array, AudiometryReport AudReport)
{
using (MemoryStream Stream = new MemoryStream())
{
Stream.Write(array, 0, (int)array.Length);
Stream.Position = 0;
using (document = WordprocessingDocument.Open(Stream, true))
{
XDocument doc = document.MainDocumentPart.GetXDocument();
List<XElement> bookmarks = doc.Descendants()
.Where(n => n.NodeType == XmlNodeType.Element && n.Name.LocalName == "bookmarkStart")
.ToList();
PropertyInfo[] reportInfo = AudReport.GetType().GetProperties();
foreach (XElement bm in bookmarks)
{
try
{
if (bm.LastAttribute.Value == "AudiometryChart")
{
string partId = InsertImage(document.MainDocumentPart);
var element = AddImageToDocument(document.MainDocumentPart, partId);
//var element = InsertImageXElement(partId);
//bm.ReplaceWith(new XElement(w + "r", element));
}
else
{
string val = reportInfo.Single(x => x.Name == bm.LastAttribute.Value).GetValue(AudReport, null).ToString();
bm.ReplaceWith(new XElement(w + "r",
new XElement(w + "t", val)));
}
}
catch
{ }
}
document.MainDocumentPart.PutXDocument();
//foreach (BookmarkStart bm in (IEnumerable<BookmarkStart>)document.MainDocumentPart.Document.Descendants<BookmarkStart>())
//{
// if (bm.Name == "AudiometryChart")
// {
// // Insert the chart object here.
// //AddImage(document);
// }
// populateStaffDetails(AudReport.Report.Employee, bm);
// populateAudiometryDetails(AudReport, bm);
//}
}
MemoryStream s = new MemoryStream();
Stream.WriteTo(s);
s.Position = 0;
return s;
}
}
The InsertImage image takes the MainDocumentPart and attaches a new ImagePart from the image I stream from the database. I pass the ID of that part back to the calling method.
private string InsertImage(MainDocumentPart docPart)
{
//DrawingsPart dp = docPart.AddNewPart<DrawingsPart>();
//ImagePart part = dp.AddImagePart(ImagePartType.Png, docPart.GetIdOfPart(dp));
ImagePart part = docPart.AddImagePart(ImagePartType.Png);
Chart cht = new ChartBuilder().DoChart(Data, new string[] { "Left", "Right", "Normal" });
using (MemoryStream ms = new MemoryStream())
{
cht.SaveImage(ms, ChartImageFormat.Png);
ms.Position = 0;
part.FeedData(ms);
}
//int count = dp.ImageParts.Count<ImagePart>();
int count = docPart.ImageParts.Count<ImagePart>();
return docPart.GetIdOfPart(part);
}
The last part is some serious nastiness that is allegdly required to add one image to one word document, but what the hell - here it is anyway:
private Run AddImageToDocument(MainDocumentPart docPart, string ImageRelId)
{
string ImageFileName = "Audiometry Chart Example";
string GraphicDataUri = "http://schemas.openxmlformats.org/drawingml/2006/picture";
long imageLength = 990000L;
long imageHeight = 792000L;
var run = new Run(
new Drawing(
new wp.Inline(
new wp.Extent() { Cx = imageLength, Cy = imageHeight },
new wp.EffectExtent()
{
LeftEdge = 19050L,
TopEdge = 0L,
RightEdge = 9525L,
BottomEdge = 0L
},
new wp.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Inline Text Wrapping Picture",
Description = ImageFileName
},
new wp.NonVisualGraphicFrameDrawingProperties(
new a.GraphicFrameLocks() { NoChangeAspect = true }),
new a.Graphic(
new a.GraphicData(
new pic.Picture(
new pic.NonVisualPictureProperties(
new pic.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = ImageFileName },
new pic.NonVisualPictureDrawingProperties()),
new pic.BlipFill(
new a.Blip() { Embed = ImageRelId },
new a.Stretch(
new a.FillRectangle())),
new pic.ShapeProperties(
new a.Transform2D(
new a.Offset() { X = 0L, Y = 0L },
new a.Extents() { Cx = imageLength, Cy = imageHeight }),
new a.PresetGeometry(
new a.AdjustValueList()) { Preset = a.ShapeTypeValues.Rectangle }))
) { Uri = GraphicDataUri }))
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U
}
));
return run;
}
So I've solved issues where the memory stream was causing problems by closing prematurely and probably a dozen other unnecessary amateur garden path problems but that image will just not show up in my document. Frustrating. Suggestions or divine inspiration very welcome right now.
(this question has been heavily edited so some answers may not relate to the wording of this question).
I've just tested your AddImageToDocument function in a small test
scenario using the following code:
string partId = ...
Run element = AddImageToDocument(newdoc.MainDocumentPart, partId);
Paragraph p = new Paragraph() { RsidParagraphAddition = "00EA6221", RsidRunAdditionDefault = "008D25CC" };
p.AppendChild(element);
newdoc.MainDocumentPart.Document.Body.Append(p);
// Save the word document here...
Everything works as expected and the image shows up in the word document.
Then I've come to the conclusion that the problem in your code must be the replacement of the bookmarkStart tag and the conversion
of the Run (containing the image) to an XElement.
So, I've modified your code in the following way (using XElement.Parse to convert
an OpenXmlElement to a XElement):
foreach (XElement bm in bookmarks)
{
try
{
if (bm.LastAttribute.Value == "AudiometryChart")
{
string partId = InsertImage(document.MainDocumentPart);
Run element = AddImageToDocument(document.MainDocumentPart, partId);
bm.ReplaceWith(XElement.Parse(element.OuterXml)); // Use XElement.Parse to convert an OpenXmlElement to an XElement.
}
else
{
... }
}
}
catch
{
}
}
The image now shows up in the word document.
Then I've analyzed the word document using the
OpenXml SDK productivity tool and found that the bookmarkEnd tags still exist in the document.
To remove those tags use the following code:
List<XElement> bookmarksEnd = doc.Descendants()
.Where(n => n.NodeType == XmlNodeType.Element && n.Name.LocalName == "bookmarkEnd")
.ToList();
foreach (XElement x in bookmarksEnd)
{
x.Remove();
}
Edit 3: :o)
Ok, I found the problem.
If you initialize the document's MemoryStream with the doc content, the buffer will be fixed in size and not editable. Just changed the init to write the doc content after creation and all seemd to work fine.
//using (MemoryStream stream = new MemoryStream (docxFile))
using (MemoryStream stream = new MemoryStream ())
{
stream.Write (docxFile, 0, docxFile.Length);
stream.Position = 0;
using (WordprocessingDocument docx = WordprocessingDocument.Open (stream, true))
{
[....]
Cheers

Using Microsoft Chart Control in ASP.NET MVC Returns a Blank Image

Using the answer Generating the Image from a Controller from this post, I created a controller action to return a chart image as seen below (the X and Y values are just there as test data):
public FileContentResult HistoryChart()
{
Chart chart = new Chart();
string[] currencies = { "ZAR", "USD", "GBP", "JPY" };
foreach (string currency in currencies)
{
Series series = new Series(currency);
series.ChartType = SeriesChartType.FastLine;
for (int x = 0; x <= 30; x++)
series.Points.AddXY(x, (x * 5));
chart.Series.Add(series);
}
using (MemoryStream ms = new MemoryStream())
{
chart.SaveImage(ms, ChartImageFormat.Png);
ms.Seek(0, SeekOrigin.Begin);
return File(ms.ToArray(), "image/png", "mychart.png");
}
}
The problem is, the image that the controller returns is blank (although it DOES return an image)
Im hoping its something simple that I have left out! Any input would be appreciated, thanks.
Hope this helps.....
I've had the same problem:
It's all to do with colors, I added some code to yours after having used another example from this blog and deduced the issue from that - so 'Thanks' to everyone....
public FileContentResult HistoryChart()
{
Chart chart = new Chart();
**chart.BackColor = Color.Transparent;**
string[] currencies = { "ZAR", "USD", "GBP", "JPY" };
foreach (string currency in currencies)
{
Series series = new Series(currency);
series.ChartType = SeriesChartType.FastLine;
for (int x = 0; x <= 30; x++)
series.Points.AddXY(x, (x * 5));
chart.Series.Add(series);
}
**ChartArea ca1 = new ChartArea("ca1");
ca1.BackColor = Color.Cyan;
chart.ChartAreas.Add(ca1);**
using (MemoryStream ms = new MemoryStream())
{
chart.SaveImage(ms, ChartImageFormat.Png);
ms.Seek(0, SeekOrigin.Begin);
return File(ms.ToArray(), "image/png", "mychart.png");
}
}
Also, you will need to ensure that your controller has:
using System.Drawing;
using System.Web.UI.WebControls;
Cheers to all...
JK.
Hi I had the same problem and it was because I was saving the image at a different time that had created it. When rendering the internal state loses.
Test generating the chart again before save image.
Sorry for my english.

Resources