Save stream to file
I have a file upload control that allows users to upload images, but before they can upload images. I want to resize thomas images to mas size 640x480. The problem is I can't figure out what to do next. This is what I have;
// CALL THE FUNCTION THAT WILL RESIZE THE IMAGE
protected void btnUploadFile_Click(object sender, EventArgs e)
{
Stream imgStream = ir.ResizeFromStream(640, fupItemImage.PostedFile.InputStream);
// What to do next?
}
// THE FUNCTION THAT WILL RESIZE IMAGE THEN RETURN AS MEMORY STREAM
public MemoryStream ResizeFromStream(int MaxSideSize, Stream Buffer)
{
int intNewWidth;
int intNewHeight;
System.Drawing.Image imgInput = System.Drawing.Image.FromStream(Buffer);
// GET IMAGE FORMAT
ImageFormat fmtImageFormat = imgInput.RawFormat;
// GET ORIGINAL WIDTH AND HEIGHT
int intOldWidth = imgInput.Width;
int intOldHeight = imgInput.Height;
// IS LANDSCAPE OR PORTRAIT ??
int intMaxSide;
if (intOldWidth >= intOldHeight)
{
intMaxSide = intOldWidth;
}
else
{
intMaxSide = intOldHeight;
}
if (intMaxSide > MaxSideSize)
{
// SET NEW WIDTH AND HEIGHT
double dblCoef = MaxSideSize / (double)intMaxSide;
intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
}
else
{
intNewWidth = intOldWidth;
intNewHeight = intOldHeight;
}
// CREATE NEW BITMAP
Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);
// SAVE BITMAP TO STREAM
MemoryStream imgMStream = new MemoryStream();
bmpResized.Save(imgMStream, imgInput.RawFormat);
// RELEASE RESOURCES
imgInput.Dispose();
bmpResized.Dispose();
Buffer.Close();
return imgMStream;
}
thank
Dumping to a file would look something like this:
using (FileStream fsOut = new FileStream("my\\file\\path.img", FileMode.Create))
using (MemoryStream msImg = new MemoryStream(ir.ResizeFromStream(640 ...)) )
{
byte[] imgData = msImg.ToArray();
fsOut.Write(imgData, 0, imgData.Length);
}
source to share
I just took a quick look, but if you've already successfully reimaged the image, then all you need to do is use the System.IO File Class namespace to save the memory stream to a file by writing bytes from the memory stream to the generated File object. If you need some sample code, let me know.
source to share
- Your current code will have resource leaks when they encounter exceptions. You should always place calls
.Dispose
in a finally or catch block (depending on whether the resource is needed to be disposed of or only disposed on error). try ... finally Dispose can be written with the keywordusing
. Save future headaches and try putting all the IDisposables in a blockusing
ortry..catch
. - Resizing images using Windows Forms will use a low quality resampler by default. This results in a mostly bad looking release; you will need to specifically set the appropriate interpolation mode (see code below).
- If you are saving images, you may run into problems with the image codec settings: for example, the default jpeg encoder has a very low output quality by default. This also needs to be installed manually (see below).
- Finally, saving the file to disk or database is actually the easiest part of it all - instead of saving to memystream, just take the stream parameter. This parameter can then be constructed to write to a file or database as needed by the caller.
I am using the following function to resize images (this will change the aspect ratio):
public static Bitmap Resize(Image oldImage, int newWidth, int newHeight)
{
Bitmap bitmap = null;
try
{
bitmap = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(oldImage, new Rectangle(0, 0, newWidth, newHeight));
}
}
catch
{
if (bitmap != null) bitmap.Dispose();
throw;
}
return bitmap;
}
Saving a file as jpeg can be done, for example, with:
public static void SaveImageAsJpeg(Image image, Stream outputStream, int quality)
{
ImageCodecInfo jpgInfo = ImageCodecInfo.GetImageEncoders()
.Where(codecInfo => codecInfo.MimeType == "image/jpeg").First();
using (EncoderParameters encParams = new EncoderParameters(1))
{
encParams.Param[0] = new EncoderParameter(Encoder.Quality,(long)quality);
//quality should be in the range [0..100]
image.Save(outputStream, jpgInfo, encParams);
}
}
which you could use through something along the lines ...
using(var origImage=Image.FromStream(inputStream, true, true))
{
//set newWidth, newHeight however you wish; determine outputFilePath
using(var newImage = Resize(origImage, newWidth, newHeight))
using(var outputStream = File.Open(outputFilePath, FileMode.Create))
SaveImageAsJpeg(newImage,outputStream, 90);
}
source to share