Reputation: 842
It seems, that if image, that is used for icon for Windows shortcuts, doesn't have aspect ratio 1:1, it will look stretched.
Left one is how it actually looks, and right one is how it should look.
I'm creating shortcut and icon programmatically from image, so I want to fix image, so it will have correct aspect ratio, but image will not look stretched. This can be achieved by adding some padding to image.
As for now, I'm simply copying image to new bitmap with correct aspect ratio, but filling new area with transparent pixels
public static Bitmap FixBitmapAspectRatio(Bitmap sourceBitmap)
{
if (sourceBitmap.Width.Equals(sourceBitmap.Height))
return sourceBitmap;
int size;
bool horizontallyOriented;
if (sourceBitmap.Width > sourceBitmap.Height)
{
horizontallyOriented = true;
size = sourceBitmap.Width;
}
else
{
horizontallyOriented = false;
size = sourceBitmap.Height;
}
var sizeDifference = Math.Abs(sourceBitmap.Width - sourceBitmap.Height);
var newBitmap = new Bitmap(size, size);
var transparentColor = Color.FromArgb(0, 0, 0, 0);
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (horizontallyOriented)
{
if (i < sizeDifference / 2 || i >= sizeDifference / 2 + sourceBitmap.Height)
{
newBitmap.SetPixel(j, i, transparentColor);
}
else
{
var originalPixel = sourceBitmap.GetPixel(j, i - sizeDifference / 2);
newBitmap.SetPixel(j, i, originalPixel);
}
}
else
{
if (i < sizeDifference / 2 || i >= sizeDifference / 2 + sourceBitmap.Width)
{
newBitmap.SetPixel(i, j, transparentColor);
}
else
{
var originalPixel = sourceBitmap.GetPixel(i - sizeDifference / 2, j);
newBitmap.SetPixel(i, j, originalPixel);
}
}
}
}
return newBitmap;
}
But I don't know, if I'm inventing a wheel. Is there any way to do this by means by standard libraries, or maybe easier way to achieve what I need?
Upvotes: 0
Views: 1927
Reputation: 63772
You really don't want to set individual pixels :)
Instead, have a look at the Graphics
class, in particular Graphics.FromImage
(that's where you paint to) and Graphics.DrawImage
(that's how you paint the scaled image).
Upvotes: 1