画像ファイルを受け取ってPNGで保存する
FileUpload1 というサーバコンポーネントを貼り付けた ASP.NET ページで、
画像ファイルを受け取ってPNGで保存するコードは、基本的には以下の2行を記述して終了。楽すぎる。
System.Drawing.Image img = System.Drawing.Image.FromStream(this.FileUpload1.FileContent, false, true /* validate image */);
img.Save(@"C:\temp\test.png", ImageFormat.Png);
強制的にある解像度にリサイズするというようなコードを書いてみた。
ただし、IndexedColor画像をリサイズすると、リサイズ先はフルカラー画像になってしまう。
.NET Framework 内に IndexedColer に変換するようなメソッドが見つけられなかった。
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
public partial class PictUploadTest : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
if (this.FileUpload1.FileBytes.Length > 0)
{
try
{
System.Drawing.Image img = System.Drawing.Image.FromStream(this.FileUpload1.FileContent, false, true /* validate image */);
Trace.Write(String.Format("width: {0}, height: {1}, format: {2}/{3}", img.Width, img.Height, GetImageFormatName(img.RawFormat), img.PixelFormat));
Bitmap bmp600dpi = new Bitmap(img, 921, 1346);
bmp600dpi.SetResolution(600, 600); // 600dpi の指定
bmp600dpi.Save(@"C:\temp\test.png", ImageFormat.Png);
bmp600dpi.Dispose();
img.Dispose();
}
catch (ArgumentException ex) // 画像フォーマットが不正な場合にこの例外となる
{
Trace.Write(ex.Message);
}
return;
}
}
public static string GetImageFormatName(ImageFormat fmt)
{
if (fmt.Guid == ImageFormat.Bmp.Guid) return "BMP";
if (fmt.Guid == ImageFormat.Emf.Guid) return "EMF";
if (fmt.Guid == ImageFormat.Exif.Guid) return "EXIF";
if (fmt.Guid == ImageFormat.Gif.Guid) return "GIF";
if (fmt.Guid == ImageFormat.Icon.Guid) return "ICON";
if (fmt.Guid == ImageFormat.Jpeg.Guid) return "JPEG";
if (fmt.Guid == ImageFormat.Png.Guid) return "PNG";
if (fmt.Guid == ImageFormat.Tiff.Guid) return "TIFF";
if (fmt.Guid == ImageFormat.Wmf.Guid) return "WMF";
return "unknown";
}
}