2016-11-11 90 views
0

我有一个图像3519 X 2495,旁边有一些徽标和文本。打开图像时,我会在中心看到徽标及其旁边的文字。我想将图片大小调整为768 X 1004,并希望徽标及其旁边的文字出现在顶部。当我调整图像大小时,我会在中心看到它旁边的标志和文字。在C#中调整图像大小并将图像中的徽标和文本对齐到顶部

有没有一种很好的方法来实现这一点在C#中。

我尝试下面的代码

Image image = Image.FromFile(@"D:\SSH\Automation\ImageResize\Diageo.jpg"); 
Bitmap bitmap = new Bitmap(768, 1004); 

Graphics graphics = Graphics.FromImage(bitmap); 
graphics.DrawImage(image, 0, 0, 768, 1004); 
bitmap.Save(@"D:\SSH\Automation\ImageResize\Diageo.png"); 
graphics.Dispose(); 

回答

0

调整图像大小,并保持它的初始纵横比使用以下代码:

注意,我使用using■从IDisposable接口而不是调用Dispose自己的因为这被认为是最佳实践并且更安全。

int maxWidth = 768; 
int maxHeight = 1004; 

using (Bitmap bitmap = new Bitmap(filePath)) 
{ 
    int width = (int)(bitmap.Width * (maxHeight/(float)bitmap.Height)); 
    int height = maxHeight; 

    if (bitmap.Height * (maxWidth/(float)bitmap.Width) <= maxHeight) 
    { 
     width = maxWidth; 
     height = (int)(bitmap.Height * (maxWidth/(float)bitmap.Width)); 
    } 

    using (Bitmap resizedBitmap = new Bitmap(width, height)) 
    { 
     resizedBitmap.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution); 

     using (Graphics g = Graphics.FromImage(resizedBitmap)) 
     { 
      g.DrawImage(bitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height); 
     } 

     //Use resizedBitmap here 
    } 
}