여기에서 이미지를 파일에서로드하고 대상 이미지를 덮어 쓰고 소문자 이름을 대문자로 변환하고 있지만 여기에서는 고정 된 크기를 사용하여 크기를 조정하고 높이 260 픽셀로 크기를 조정하고 이미지 너비를 설정하지 않고 종횡비를 유지해야합니다.
//--------------------------------------------------------------------------------//
private void ProcessImage()
{
if (File.Exists(pictureBox1.ImageLocation))
{
string SourceImagePath = pictureBox1.ImageLocation;
string ImageName = Path.GetFileName(SourceImagePath).ToUpper();
string TargetImagePath = Properties.Settings.Default.ImageTargetDirectory + "\\" + ImageName;
//Set the image to uppercase and save as uppercase
if (SourceImagePath.ToUpper() != TargetImagePath.ToUpper())
{
using (Image Temp = Image.FromFile(SourceImagePath))
{
// my problem is here, i need to resize only by height
// and maintain aspect ratio
Bitmap ResizedBitmap = resizeImage(Temp, new Size(175, 260));
//ResizedBitmap.Save(@TargetImagePath);
ResizedBitmap.Save(@TargetImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
pictureBox1.ImageLocation = @TargetImagePath;
File.Delete(SourceImagePath);
}
}
}
//--------------------------------------------------------------------------------//
private static Bitmap resizeImage(Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return b;
}
//--------------------------------------------------------------------------------//
너비를 비례 적으로 유지하면서 이미지를 지정된 높이로 크기를 조정하고 싶습니까?
/// <summary>
/// Resize the image to have the selected height, keeping the width proportionate.
/// </summary>
/// <param name="imgToResize"></param>
/// <param name="newHeight"></param>
/// <returns></returns>
private static Bitmap resizeImage(Image imgToResize, int newHeight)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercentH = ((float)newHeight / (float)sourceHeight);
int destWidth = Math.Max((int)Math.Round(sourceWidth * nPercentH), 1); // Just in case;
int destHeight = newHeight;
Bitmap b = new Bitmap(destWidth, destHeight);
using (Graphics g = Graphics.FromImage((Image)b))
{
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
}
return b;
}
참고- 예외 발생시 처리를 보장하므로 명시 적으로를 삭제하는 대신 문을 Graphics g
사용하십시오 using
.
업데이트 호출 메서드 내에서 명령문으로 래핑 ResizedBitmap
하는 것이 좋습니다 using
.
업데이트 2 지정된 최대 크기로 JPG를 저장하는 방법을 찾을 수 없습니다. 할 수있는 일은 지정된 품질로 저장하고 파일이 너무 크면 낮은 품질로 다시 시도하는 것입니다.
public static void SaveJpegWithSpecifiedQuality(this Image image, string filename, int quality)
{
// http://msdn.microsoft.com/en-us/library/ms533844%28v=vs.85%29.aspx
// A quality level of 0 corresponds to the greatest compression, and a quality level of 100 corresponds to the least compression.
if (quality < 0 || quality > 100)
{
throw new ArgumentOutOfRangeException("quality");
}
System.Drawing.Imaging.Encoder qualityEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters encoderParams = new EncoderParameters(1);
EncoderParameter encoderParam = new EncoderParameter(qualityEncoder, (long)quality);
encoderParams.Param[0] = encoderParam;
image.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParams);
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
있습니다 크기 조정 알고리즘의 품질 은 AS 같은 것이 아니다 절약의 파일 압축의 품질 . 두 작업 모두 손실 이 발생 합니다. 최상 품질 알고리즘 (위에 표시하도록 업데이트 됨)으로 크기를 조정 한 다음 작동하는 것을 찾을 때까지 저장 품질을 실험하는 것이 좋습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다