0
これは、C#で正方形のサムネイルを生成するためのコードです。下のコードでさらに改善ができますか?
このタイプのものは前もってコード化していません。 このコードは頻繁に使用されるので、私はこれを実際に運用する前に確認しています。
あなたは何か悪いことを見ますか、さらに改善することができますか?
基本的には、いくつかのフォルダにサムネイルのセットがあります。 これらのサムネイルは正方形ではなく、すべてを正方形にする必要があります。 これは、フォルダ内の各ファイルに対してループで呼び出されます。
これは私がそれを呼び出す方法です:
SaveSquareThumb(75, "C:\storage\images\temp\thumbs", "C:\storage\images\thumbs");
public static void SaveSquareThumb(int squareSize, string sourcePath, string savePath)
{
using (Bitmap srcImage = new Bitmap(sourcePath))
{
int width = srcImage.Width;
int height = srcImage.Height;
int x = 0;
int y = 0;
//Determine dimensions of resized version of the image
if (width > height)
{
width = (int)Decimal.Round(Convert.ToDecimal((decimal)squareSize * ((decimal)width/(decimal)height)), 0);
height = squareSize;
// moves cursor so that crop is more centered
x = Convert.ToInt32(Math.Ceiling(((decimal)(width - height)/2M)));
}
else if (height > width)
{
height = (int)Decimal.Round(Convert.ToDecimal((decimal)squareSize * ((decimal)height/(decimal)width)), 0);
width = squareSize;
// moves cursor so that crop is more centered
y = Convert.ToInt32(Math.Ceiling(((decimal)(height - width)/2M)));
}
else
{
width = squareSize;
height = squareSize;
}
// required in case thumbnail creation fails?
Image.GetThumbnailImageAbort dummyCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg");
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
//get thumbnail from source image
using (Image thumb = srcImage.GetThumbnailImage(width, height, null, System.IntPtr.Zero))
{
//Create a Crop Frame to apply to the Resized Image
using (Bitmap myBitmapCropped = new Bitmap(squareSize, squareSize))
{
using (Graphics myGraphic = Graphics.FromImage(myBitmapCropped))
{
//Apply the Crop to the Resized Image
myGraphic.DrawImage(thumb, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
//Save the Croped and Resized image as a new square thumnail
myBitmapCropped.Save(savePath, codecInfo, encoderParams);
}
}
}
}
}
はおそらく上の所属しますhttp://codereview.stackexchange.com/ –