Showing posts with label upload. Show all posts
Showing posts with label upload. Show all posts

Saturday, November 3, 2007

Uploading and resizing an image to Sql Server 2005

So here's the first technical post.

This code has been designed to work on a simple ASP form, but you can adapt it to work on Windows application.

First I'll start with the resizing part;


public byte[] ResizeImg(System.Drawing.Image UploadedImage, int UploadedImageWidth, int UploadedImageHeight, int DesiredWidth)
{
int NewWidth;
int NewHeight;

//determine if landscape or portrait
if (UploadedImageWidth >= UploadedImageHeight)
{
intMaxSide = UploadedImageWidth;
}
else
{
intMaxSide = UploadedImageHeight;
}

if (UploadedImageWidth > DesiredWidth)
{
//set new width and height
double dblCoef = DesiredWidth / (double)intMaxSide;
NewWidth = Convert.ToInt32(dblCoef * UploadedImageWidth);
NewHeight = Convert.ToInt32(dblCoef * UploadedImageHeight);
}
else
{
NewWidth = UploadedImageWidth;
NewHeight = UploadedImageHeight;
}

//create new bitmap
Bitmap bmpResized = new Bitmap(UploadedImage, NewWidth, NewHeight);

System.IO.MemoryStream stream = new System.IO.MemoryStream();
bmpResized.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] blob = stream.ToArray();
stream.Close();

return blob;
}


This method will resize and transform an Image to byte[] so that we can upload it on Sql Server.
The parameter DesiredWidth represents the max Width or Height (dépending if the image is landscape or portrait).

If you prefer to fix the width or height (wherever it's landscape or portrait), you simply have to replace these lines


//determine if landscape or portrait
if (UploadedImageWidth >= UploadedImageHeight)
{
intMaxSide = UploadedImageWidth;
}
else
{
intMaxSide = UploadedImageHeight;
}


with;


//Fix the width
int intMaxSide = UploadedImageWidth;
or

//Fix the height
int intMaxSide = UploadedImageHeight;



Now on the ASP form, you add a FileUpload control and a Button.
On the Button_Click event, we'll upload the resized picture;




//Determine type and filename of uploaded image
string UploadedImageType = FileUploadPhoto.PostedFile.ContentType.ToString().ToLower();
string UploadedImageFileName = FileUploadPhoto.PostedFile.FileName;

//Create an image object from the uploaded file
System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(FileUploadPhoto.PostedFile.InputStream);

//Determine width and height of uploaded image
int UploadedImageWidth = (int)UploadedImage.PhysicalDimension.Width;
int UploadedImageHeight = (int)UploadedImage.PhysicalDimension.Height;

byte[] image = myTools.ResizeImg(UploadedImage, UploadedImageWidth, UploadedImageHeight, 300);

//Call a stored procedure through a WebService
myService.UpdatePicture(image, FileUploadPhoto.PostedFile.ContentType, id);

If you have any questions, you know where to post ;)