How to Crop Image And Overwrite Exiting - c#

protected void btnCropIt_Click(object s, EventArgs e)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("../upload/" + u.Avatar));
var m = cropImage(img, new Rectangle(0, 0, 50, 50));
System.IO.File.Delete(Server.MapPath("../upload/" + u.Avatar));
m.Save(Server.MapPath("../upload/" + u.Avatar));
}
private static System.Drawing.Image cropImage(System.Drawing.Image img, Rectangle cropArea)
{
Bitmap bmpImage = new Bitmap(img);
Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
return (System.Drawing.Image)(bmpCrop);
}
System.IO.File.Delete(Server.MapPath("../upload/" + u.Avatar));
This line of code throws exception that it can't delete image, it's used by another process. Any Idea? How to overwrite it?

Your code is still using it. FromFile() keeps it locked until the image is disposed. It's kind of an obscure semantic, but the MSDN documentation does mention it.
You might try img.Finalize() right after cropImage() as a simple fix. If that doesn't work, pull it in with a FileStream, use the System.Drawing.Bitmap Stream constructor overload, then close the FileStream immediately.

Related

Cannot Clone Bitmap after Stream Disposed

I load a bitmap from a DataStream. I try to return the loaded bitmap from a method, and later use it as a source to clone a new bitmap. Unfortunately, the Clone() call results in an OutOfMemoryException. Through testing I realized that Clone() succeeds until the underlying data stream is disposed.
How can I create a bitmap that exists independent from the stream it was loaded from?
DxScreenCapture cap = new DxScreenCapture();
var surface = cap.CaptureScreen();
Bitmap png;
Rectangle rect;
PixelFormat fmt;
using (DataStream stream = Surface.ToStream(surface, ImageFileFormat.Bmp))
{
png = new Bitmap(stream);
fmt = png.PixelFormat;
rect = new Rectangle(911, 170, 32, 14);
// Works
Bitmap rgn1 = png.Clone(rect, fmt);
}
// Throws OutOfMemoryException
Bitmap rgn2 = png.Clone(rect, fmt);
Building on Hans' comment, I simply created a new bitmap from the original one.
Bitmap copy;
using (DataStream stream = Surface.ToStream(surface, ImageFileFormat.Bmp))
{
Bitmap orig = new Bitmap(stream);
copy = new Bitmap(orig);
}
// Able to use copy after stream is disposed

Issue capturing windows form drawing to image C#

I'm trying to draw a few objects to a windows form, then create a image of that form and save it to a folder.
This is a two part question... Why isn't the image that is being drawn to the windows form showing up on the created image? Also second question is, how can I create an image of the windows form drawing, from say point 0,0 to point 500,500 without a background....
Here is the code I have at the moment....
Form draw = new Drawing(); // Opens the drawing form
draw.Show();
try
{
//Try to draw something...
System.Drawing.Pen myPen;
myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics = draw.CreateGraphics();
formGraphics.DrawLine(myPen, 0, 0, 500, 500);
myPen.Dispose();
formGraphics.Dispose();
var path = this.outputFolder.Text; // Create variable with output path
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path); // Create path if it doesn't exist
}
using (var bitmap = new Bitmap(draw.Width, draw.Height)) // Creating the .bmp file from windows form
{
draw.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(path + "\\" + i + ".bmp");
}
}
catch { }
Can you see anything wrong here? What seems to be prohibiting the drawings to be saved to a .bmp file?
Thank in advance!
I ended up using the example shown here Saving System.Drawing.Graphics to a png or bmp
Form draw = new Drawing(); // Opens the drawing form
draw.Show();
try
{
var path = this.outputFolder.Text; // Path where images will be saved to
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path); // Create a directory if it does not already exist
}
Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
System.Drawing.Pen myPen;
myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
g.DrawLine(myPen, 0, 0, 1024, 1024);
bitmap.Save(path + "\\" + i + ".png", ImageFormat.Png);
}
catch { }
And that has worked flawlessly for me now :D

How to re-size an image with asp.net C# without saving it

I use this code to re-size images, but my problem is that I have to save the original picture then re-size that! How can I re-size a picture without saving it?
I want to re-size the picture first and then save it.
FileUpload1.SaveAs("saveOriginalFileFirstHere");
string thumbpath = "where resized pic should be saved";
MakeThumbnails.makethumb("saveOriginalFileFirstpath", thumbpath);
public static void makethumb(string savedpath, string thumbpath)
{
int resizeToWidth = 200;
int resizeToHeight = 200;
Graphics graphic;
//Image photo; // your uploaded image
Image photo = new Bitmap(savedpath);
// Image photo = new j
Bitmap bmp = new Bitmap(resizeToWidth, resizeToHeight);
graphic = Graphics.FromImage(bmp);
graphic.InterpolationMode = InterpolationMode.Default;
graphic.SmoothingMode = SmoothingMode.Default;
graphic.PixelOffsetMode = PixelOffsetMode.Default;
graphic.CompositingQuality = CompositingQuality.Default;
graphic.DrawImage(photo, 0, 0, resizeToWidth, resizeToHeight);
bmp.Save(thumbpath);
}
Use the InputStream property of the uploaded file instead:
I have modified your code to do so:
EDIT: You really should dispose of your IDisposables, such as your bitmaps and the stream, to avoid memory leakage. I have updated my code, so it will properly dispose these resources after it's done with them.
string thumbpath = "where resized pic should be saved";
MakeThumbnails.makethumb(FileUpload1.InputStream, thumbpath);
public static void makethumb(Stream stream, string thumbpath)
{
int resizeToWidth = 200;
int resizeToHeight = 200;
using (stream)
using (Image photo = new Bitmap(stream))
using (Bitmap bmp = new Bitmap(resizeToWidth, resizeToHeight))
using (Graphics graphic = Graphics.FromImage(bmp))
{
graphic.InterpolationMode = InterpolationMode.Default;
graphic.SmoothingMode = SmoothingMode.Default;
graphic.PixelOffsetMode = PixelOffsetMode.Default;
graphic.CompositingQuality = CompositingQuality.Default;
graphic.DrawImage(photo, 0, 0, resizeToWidth, resizeToHeight);
bmp.Save(thumbpath);
}
}
This should work the way you want it to, if it doesn't, or if anything is unclear, please let me know.

Change format of unmanaged image byte array

I have this code (C#):
unsafe private Bitmap Test()
{
Bitmap test = null;
byte[] data = memRenderAll.CurrentData;
fixed (byte* m_pBuffer = _data)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
Bitmap a = new Bitmap(720, 576, 2160, System.Drawing.Imaging.PixelFormat.Format24bppRgb, new IntPtr(m_pBuffer));
a.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
test =(Bitmap) Image.FromStream(ms);
a.Dispose();
}
}
return _test;
}
By saving the stream as this:
a.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
I get a 10:1 reduction is size.
Is there a way of avoiding this:
a.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
and specifying it somewhere/somehow in:
Bitmap a = new Bitmap(720, 576, 2160, System.Drawing.Imaging.PixelFormat.Format24bppRgb, new IntPtr(m_pBuffer));
as I would like to create the Bitmap only once.
thanks,
Andrew
I think its impossible todo in one code line using standard System.Drawing.
You use that constructor: http://msdn.microsoft.com/en-us/library/zy1a2d14(v=vs.110).aspx
Your code:
new Bitmap(720, 576, 2160, System.Drawing.Imaging.PixelFormat.Format24bppRgb, new IntPtr(m_pBuffer));
What does it mean? Bitmap read memory pointed by m_pBuffer using fixed width, height, stride and pixel format. You can't read it as jpeg, because jpeg - image zipping fomat. Look on it: http://en.wikipedia.org/wiki/JPEG#JPEG_codec_example . Jpeg codec need all your image for ziping, it can't zip parts and join them after.

MemoryStream is null when creating a new Bitmap from Stream

I am trying to create a Bitmap from a stream that has a PDF document saved with-in the stream, but I keep getting argument null exception. The MS is not null and it is positioned at 0. So I'm lost as to what else to do.
I'm testing the functionality by using a windows forms application sandbox but I cannot get the memory stream to save to a Bitmap.
Can someone point out to me where I'm going wrong?
private async void Form1_Load(object sender, EventArgs e)
{
//4355,4373
IElevation elev = await ElevationManager.GetElevationAsync(4355);
PdfSharp.Pdf.PdfDocument pdfDoc =
await (await AlumCloudPlans.Manager.GetLabelsAsync(elev)).GetPDF(new SheetInfo(/*settings for PDF, Img printing is different*/3, 10, 240, 95, 780, 1000));
System.IO.Stream ms = new MemoryStream();
pdfDoc.Save(ms, false);
ms.Position = 0;
Bitmap bm = new Bitmap(ms); <---------(Error right here, says argument null)
this.AutoScroll = true;
this.pictureBox1.Image = bm;
this.pictureBox1.BackColor = Color.White;
this.Size = new System.Drawing.Size(bm.Width, (bm.Height + 50) / 2);
this.pictureBox1.Size = new System.Drawing.Size(bm.Width, bm.Height + 5);
}
What am i missing here?
You're trying to open stream containing a PDF document, Bitmap constructor is expecting image data. PDFSharp can only create PDF document, but can't render it to image.
To render PDF document to bitmap, you have to use other libraries, e.g. lib-pdf, mupdf-converter or .NET wrapper for Ghostscript.

Categories

Resources