asp.Net(C#)圧縮画像、画像テンプレートの高さと幅を指定できます

3490 ワード

 
  
//
// : 、 、 、
// :
public static void MakeSmallImg(System.IO.Stream fromFileStream, string fileSaveUrl, System.Double templateWidth, System.Double templateHeight)
{
// ,
System.Drawing.Image myImage = System.Drawing.Image.FromStream(fromFileStream, true);
// 、
System.Double newWidth = myImage.Width, newHeight = myImage.Height;
//
if (myImage.Width > myImage.Height || myImage.Width == myImage.Height)
{
if (myImage.Width > templateWidth)
{
// ,
newWidth = templateWidth;
newHeight = myImage.Height * (newWidth / myImage.Width);
}
}
//
else
{
if (myImage.Height > templateHeight)
{
// ,
newHeight = templateHeight;
newWidth = myImage.Width * (newHeight / myImage.Height);
}
}
//
System.Drawing.Size mySize = new Size((int)newWidth, (int)newHeight);
// bmp
System.Drawing.Image bitmap = new System.Drawing.Bitmap(mySize.Width, mySize.Height);
//
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
// ,
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//
g.Clear(Color.White);
//
g.DrawImage(myImage, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
new System.Drawing.Rectangle(0, 0, myImage.Width, myImage.Height),
System.Drawing.GraphicsUnit.Pixel);
///
//System.Drawing.Graphics G=System.Drawing.Graphics.FromImage(bitmap);
//System.Drawing.Font f=new Font(" ",10);
//System.Drawing.Brush b=new SolidBrush(Color.Black);
//G.DrawString("myohmine",f,b,10,10);
//G.Dispose();
///
//System.Drawing.Image copyImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("pic/1.gif"));
//Graphics a = Graphics.FromImage(bitmap);
//a.DrawImage(copyImage, new Rectangle(bitmap.Width-copyImage.Width,bitmap.Height-copyImage.Height,copyImage.Width, copyImage.Height),0,0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
//copyImage.Dispose();
//a.Dispose();
//copyImage.Dispose();
//
bitmap.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
g.Dispose();
myImage.Dispose();
bitmap.Dispose();
}
 
  
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = " ";
// fileDialog.Filter = "excel files (*.xls)|*.xls";
fileDialog.FilterIndex = 1;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{

System.IO.FileStream file =System.IO.File.Open(fileDialog.FileName,System.IO.FileMode.Open);
System.IO.Stream strea = file;
file.Close();
MakeSmallImg(strea, " .jpg", 150, 150);
// file.Close();

}
}