ASP.NET MVC Error when saving image - c#

I am trying to save an image I've created from Bitmap in a given Path in my project, but I get this error: Additional information: A generic error occurred in GDI+.
This is the code :
public void SaveCaptchaImage(string name)
{
Bitmap image = new Bitmap(128, 64);
string path = "/content/images";
if (System.IO.File.Exists(path + name))
System.IO.File.Delete(path + name);
using (Pen myPen = new Pen(Color.Red, 5))
using (Brush myBrush = new SolidBrush(Color.Silver))
using (Font myFont = new Font("Arial", 16))
using (Graphics graphObject = Graphics.FromImage(image))
{
graphObject.FillRectangle(myBrush, new Rectangle(0, 0, 128, 64));
graphObject.DrawString(GetRandomCaptcha(), myFont, myBrush, new Point(20, 20));
image.Save(path + name + ".png", ImageFormat.Png);
}
image.Dispose();
}
The exception occurs at this line:
image.Save(path + name + ".png", ImageFormat.Png);
What can I do to solve this problem ?
Edit: I don't get why I got downvoted, but ok.

Wrap your path with Server.MapPath like:
image.Save(HttpContext.Current.Server.MapPath(Path.Combine(path, name + ".png")), ImageFormat.Png);
to get absolute path instead of relative.
and use Path.Combine method like #stuartd suggested in comments.

Related

Barcode ASP.NET C# Issue

I have this code for generating barcode when page is loaded.(code below) txtBarcodeBlack.Text content is pulled from SQL Server Database as varchar.
I have a button submit that will do another process like saving the txtBarcodeBlack.text to database. My problem is when I press the button, it gives me this Problem please help. I'm stuck for 2 days.
private void loadBlackBarcode() {
//barcode black
//txtBarcodeBlack.Text = vBarcodeBlack;
string barCodeBlack = txtBarcodeBlack.Text;
System.Web.UI.WebControls.Image imgBarCodeBlack = new System.Web.UI.WebControls.Image();
using (Bitmap bitMap = new Bitmap(barCodeBlack.Length * 40, 80))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
Font oFont = new Font("IDAutomationHC39M", 16);
PointF point = new PointF(2f, 2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString("*" + barCodeBlack + "*", oFont, blackBrush, point);
}
using (MemoryStream ms = new MemoryStream(100000))
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCodeBlack.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCodeBlack);
}
}
<div class="col-xs-12 col-sm-12 col-lg-12" style="margin-bottom:20px;">
<h3>Digital Black</h3>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
UPDATE
Okay I tried searching for other solution, and I found the answer.
I changed this line:
using (Bitmap bitMap = new Bitmap(barCodeBlack.Length * 40, 80))
to this line:
using (Bitmap bitMap = new Bitmap(800, 80))
for some reason the new Bitmap does not accept variable inside the parameter, so I guess I need to hard code my measurement of the barcode.

How to delete image file from specific folder path?

i created two images 1st one is Barcode Image and 2nd is SkuImage after that I Merged It in 3rd image(final Image). after Successfully Merged
i want to delete Barcode Image and Sku image from Specific folder, but when i try to delete image file it Gives me a error i.e "The process cannot access the file \Path\ because it is being used by another process".
before deleting i disposed the image like this "SkuImage.Dispose()" but it doesnt delete. How do i delete this?
barcodeImage = b.Encode(BarcodeLib.TYPE.CODE128, "001234", Color.Black, Color.White, 113, 18);
Bitmap SkuImage = new Bitmap(113, 18, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
RectangleF rectf = new RectangleF(10, 5, 113, 18);
Graphics graphics = Graphics.FromImage(SkuImage);
// SkuImage.SetPixel(10,10,Color.Blue);
graphics.DrawString(StringToEncode, new Font("Arial", 4), Brushes.Black, rectf);
b.SaveImage(MemStream, savetype);
MemStream.Close();
barcodeImage.Dispose();
SkuImage.Save(imgSkupath);
SkuImage.Dispose();
g.Clear(Color.White); //here change BG color of Image
g.DrawImage(Image.FromFile("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/" + Filename), new Point(15, 15));
g.DrawImage(Image.FromFile("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpg"), new Point(25, 30));
img.Save("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/FinalImage.jpeg", ImageFormat.Jpeg);
File.Delete("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpg");
File.Delete("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/" + Filename);
You should dispose every class that implements IDisposable. Then you can delete the image file.
string Filename = "Barcodeimage" + i + ".jpeg";
string imgsavepath = "E:\\Pankaj\\BarcodeDemo\\BarcodeDemo\\BarcodeImage\\" + "BarcodeImg.jpeg";
string imgSkupath = "E:\\Pankaj\\BarcodeDemo\\BarcodeDemo\\BarcodeImage\\" + "Sku.jpeg";
BarcodeLib.SaveTypes savetype = BarcodeLib.SaveTypes.UNSPECIFIED;
savetype = BarcodeLib.SaveTypes.JPG;
System.IO.FileStream MemStream = new FileStream(imgsavepath, FileMode.Create, FileAccess.Write);
System.Drawing.Image barcodeImage = null;
//Bitmap FinalImage = null;
BarcodeLib.Barcode b = new BarcodeLib.Barcode();
//b.IncludeLabel = true;
b.LabelFont = new Font("Arial", 5);
string sku = "SKU:VXN4214IN";
string StringToEncode = "16280/" + i + ' ' + sku;
Image img = new Bitmap(130, 50); //final image
Graphics g = Graphics.FromImage(img);
barcodeImage = b.Encode(BarcodeLib.TYPE.CODE128, "001234", Color.Black, Color.White, 113, 18);
Bitmap SkuImage = new Bitmap(113, 18, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
RectangleF rectf = new RectangleF(10, 5, 113, 18);
Graphics graphics = Graphics.FromImage(SkuImage);
// SkuImage.SetPixel(10,10,Color.Blue);
graphics.DrawString(StringToEncode, new Font("Arial", 4), Brushes.Black, rectf);
b.SaveImage(MemStream, savetype);
MemStream.Close();
barcodeImage.Dispose();
SkuImage.Save(imgSkupath);
graphics.Dispose();
SkuImage.Dispose();
g.Clear(Color.White); //here change BG color of Image
System.IO.FileStream fileStream1 = new FileStream("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/BarcodeImg.jpeg", FileMode.Open, FileAccess.Read);
System.IO.FileStream fileStream2 = new FileStream("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpeg", FileMode.Open, FileAccess.Read);
g.DrawImage(Image.FromStream(fileStream1), new Point(15, 15));
g.DrawImage(Image.FromStream(fileStream2), new Point(25, 30));
// g.DrawImage(Image.FromFile("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/" + Filename), new Point(15, 15));
//g.DrawImage(Image.FromFile("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpg"), new Point(25, 30));
img.Save("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/"+Filename, ImageFormat.Jpeg);
fileStream1.Close();
fileStream2.Close();
g.Dispose();
File.Delete("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpeg");
File.Delete("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/BarcodeImg.jpeg");
Dim _strImagePath = ""
Dim _strImageName = "image.jpg"
'Get the path
_strImagePath = "YOUR_IMAGE_PATH"
'Delete the image physically
Dim strImageName As New FileInfo(_strImagePath & _strImageName)
If strImageName.Exists Then
strImageName.Delete()
End If

Move dynamically created image to a new page

I can dynamically create a barcode using sample tutorials.
This block of code is in a loop and generates a number of images determined by user input. The image is in a place holder and is displayed on the same webpage.
I want the user to be able to have all the images on a separate page or file for them to print, but I'm not quite sure the best approach to do that. I tried placing it in a session, but I only get 1 image as opposed to the amount the user entered.
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (Bitmap bitMap = new Bitmap(barCode.Length * 27, 100))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
Font oFont = new Font("IDAutomationHC39M", 16);
PointF point = new PointF(2f, .2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString("*" + barCode + "*", oFont, blackBrush, point);
}
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bitMap.Save(ms, ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
plBarCode.Controls.Add(imgBarCode);
}

How to save a Bitmap using filestream

I have created a bitmap and I want to save it in my upload folder. How can I do this?
My Code:
public FileResult image(string image)
{
var bitMapImage = new Bitmap(Server.MapPath("/Content/themes/base/images/photo.png"));
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
graphicImage.DrawString(image, new Font("Trebuchet MS,Trebuchet,Arial,sans-serif", 10, FontStyle.Bold), SystemBrushes.WindowFrame, new Point(15, 5));
graphicImage.DrawArc(new Pen(Color.Red, 3), 90, 235, 150, 50, 0, 360);
MemoryStream str = new MemoryStream();
bitMapImage.Save(str, ImageFormat.Png);
return File(str.ToArray(), "image/png");
}
The path I will use:
string mynewpath = Request.PhysicalApplicationPath + "Upload\\";
The Bitmap class has several overloads of the Save method. One of them takes a file name as parameter which means that you can use
bitMapImage.Save(mynewpath + "somefilename.png", ImageFormat.Png);
the question seems to be in conflict with your code (there you load a file from your images and return it) - anyway: there is a "Save" method on your Image-classes so just use this with the same Server.MapPath trick ... just make sure that the ASP.NET account has access/write rights for your target-folder:
string mynewpath = Request.PhysicalApplicationPath + "Upload\\myFile.png";
bitMapImage.Save(mynewpath);
remark: this is using your path but I don't know if this is really the right choice for your problem - as I said: MapPath should be the saver bet.

Can you open a JPEG, add text, and resave as a JPEG in .NET?

I want to write a small program in .NET 4.0 that will open a .jpg (or .jpeg) file, add a line of text to the image, and then resave the image as a .jpg. Does anyone know the easiest way to do this?
Thanks for any help.
Something like this:
var filePath = #"D:\Pictures\Backgrounds\abc.jpg";
Bitmap bitmap = null;
// Create from a stream so we don't keep a lock on the file.
using (var stream = File.OpenRead(filePath))
{
bitmap = (Bitmap)Bitmap.FromStream(stream);
}
using (bitmap)
using (var graphics = Graphics.FromImage(bitmap))
using (var font = new Font("Arial", 20, FontStyle.Regular))
{
// Do what you want using the Graphics object here.
graphics.DrawString("Hello World!", font, Brushes.Red, 0, 0);
// Important part!
bitmap.Save(filePath);
}
var myBitmap = new Bitmap("C:\\myImage.jpg");
var g = Graphics.FromImage(myBitmap);
g.DrawString("My\nText", new Font("Tahoma", 40), Brushes.White, new PointF(0, 0));

Categories