// adapted from http://snippets.dzone.com/posts/show/1485
public static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
{
System.Drawing.Image original = System.Drawing.Image.FromStream(new MemoryStream(imageFile));
int targetH, targetW;
if (original.Height > original.Width)
{
targetH = targetSize;
targetW = (int)(original.Width * ((float)targetSize / (float)original.Height));
}
else
{
targetW = targetSize;
targetH = (int)(original.Height * ((float)targetSize / (float)original.Width));
}
System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(new MemoryStream(imageFile));
// Create a new blank canvas. The resized image will be drawn on this canvas.
Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(72, 72);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel);
// Save out to memory and then to a file. We dispose of all objects to make sure the files don't stay locked.
MemoryStream mm = new MemoryStream();
bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
original.Dispose();
imgPhoto.Dispose();
bmPhoto.Dispose();
grPhoto.Dispose();
return mm.GetBuffer();
}
public int uploadImage()
{
int photonum = 1;
Stream imgStream = UploadFile.PostedFile.InputStream;
int imgLen = UploadFile.PostedFile.ContentLength;
string imgContentType = UploadFile.PostedFile.ContentType;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData, 0, imgLen);
byte[] imgBinaryData2 = ResizeImageFile(imgBinaryData, 200);
string imgName = UploadFile.PostedFile.FileName;
int newImageLen = imgBinaryData2.Length;
String cdate = DateTime.Now.ToString();
int RowsAffected = SaveToDB(imgName, imgBinaryData2, imgContentType, newImageLen, cdate);
if (RowsAffected > 0)
{
OleDbDataReader rdr = null;
strConnection = ConfigurationManager.AppSettings["DBKey"];
String strSQL = "SELECT img_id FROM tblImages where created_date='" + cdate + "'";
conUser = new OleDbConnection(strConnection);
if (conUser.State.ToString().Equals("Open")) { conUser.Close(); }
conUser.Open();
cmdUser = new OleDbCommand(strSQL, conUser);
rdr = cmdUser.ExecuteReader();
while (rdr.Read())
{
photonum = rdr.GetInt32(0);
}
return photonum;
}
return -1;
}
Tuesday, November 24, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment