I have an ASP Image control that I want to save to a specific folder.
Image1.ImageUrl = "~/fa/barcode.aspx?d=" + Label1.Text.ToUpper();
This is basically what barcode.aspx does:
Bitmap oBitmap = new Bitmap(w, 100);
// then create a Graphic object for the bitmap we just created.
Graphics oGraphics = Graphics.FromImage(oBitmap);
oGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
oGraphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
// Let's create the Point and Brushes for the barcode
PointF oPoint = new PointF(2f, 2f);
SolidBrush oBrushWrite = new SolidBrush(Color.Black);
SolidBrush oBrush = new SolidBrush(Color.White);
// Now lets create the actual barcode image
// with a rectangle filled with white color
oGraphics.FillRectangle(oBrush, 0, 0, w, 100);
// We have to put prefix and sufix of an asterisk (*),
// in order to be a valid barcode
oGraphics.DrawString("*" + Code + "*", oFont, oBrushWrite, oPoint);
Response.ContentType = "image/jpeg";
oBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
How do I save it to a folder (~/fa/barcodeimages/)? So far here’s what I tried:
WebClient webClient = new WebClient();
string remote = "http://" + Request.Url.Authority.ToString() + "/fa/barcode.aspx?d=" + Label1.Text.ToUpper();
string local = Server.MapPath("barcodeimages/" + Label1.Text.ToUpper() + ".jpeg");
webClient.DownloadFile(remote, local);
But it does not work, I always get a corrupted .jpeg file. And it seems inefficient.
It looks like the problem is that your business logic – the code required to generate a barcode image – is in the wrong place.
You should keep that business logic away from the presentation logic of your aspx page (which is about serving an image to respond to a URL), and move the
Bitmapcreation logic to somewhere that both the “serve a barcode” and “save a barcode to disk” code can get at it. That could be in a different business logic assembly, or it could simply be in a separate class within the same project. The main thing is that you want it in a reusable place.At that point, your aspx code changes to something like:
and your saving code changes to something like:
Here,
barcodeGeneratorwould ideally be a depedency-injected instance of yourBarcodeGeneratorclass (or whatever it turns out to be). If you’re not using dependency injection, you could create a new instance directly, specifying the font etc each time – it’s not as pleasant, but it should work okay.