问题
Is there anyone who knows a way to resize images on the .net 2.0 Compact Framework?
I want to be able to get images, taken with the camera on my phone, from the phones memory, resize them and then upload them to a webservice so I acctually don't need to store the resized images on disk.
回答1:
This is the C# code I use to resize images in my .NET CF 2.0 applications:
public static Image ResizePicture( Image image, Size maxSize )
{
if( image == null )
throw new ArgumentNullException( "image", "Null passed to ResizePictureToMaximum" );
if( ( image.Width > maxSize.Width ) || ( image.Height > maxSize.Height ) )
{
Image resizedImage = new Bitmap( maxSize.Width, maxSize.Height );
using( Graphics graphics = Graphics.FromImage( resizedImage ) )
{
graphics.Clear( Color.White );
float widthRatio = maxSize.Width / image.Width;
float heightRatio = maxSize.Height / image.Height;
int width = maxSize.Width;
int height = maxSize.Height;
if( widthRatio > heightRatio )
{
width = ( int )Math.Ceiling( maxSize.Width * heightRatio );
}
else if( heightRatio > widthRatio )
{
height = ( int )Math.Ceiling( maxSize.Height * widthRatio );
}
graphics.DrawImage(
image,
new Rectangle( 0, 0, width, height ),
new Rectangle( 0, 0, image.Width, image.Height ),
GraphicsUnit.Pixel );
}
return resizedImage;
}
return image;
}
回答2:
Graphics.FromImage should work for jpg images, however you may run into memory problems.
Have a look at this forum post for some ideas.
回答3:
The c# code is missing a cast in
float widthRatio = (float) maxSize.Width / image.Width;
float heightRatio = (float) maxSize.Height / image.Height;
and also for centering the image:
graphics.DrawImage(image, new Rectangle((maxSize.Width - width) / 2, (maxSize.Height -height ) / 2, width, height), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
回答4:
THis vb.net works on Windows Mobile. Only constraint: Large Bitmaps cause an OutOfMemoryException when opened:
Private Function ResizedImage(ByVal image As Bitmap, ByVal maxW As Integer, ByVal maxH As Integer) As Bitmap
Dim divideByH, divideByW As Double
Dim width, height As Integer
divideByW = image.Width / maxW
divideByH = image.Height / maxH
If divideByW > 1 Or divideByH > 1 Then
If divideByW > divideByH Then
width = CInt(CDbl(image.Width) / divideByW)
height = CInt(CDbl(image.Height) / divideByW)
Else
width = CInt(CDbl(image.Width) / divideByH)
height = CInt(CDbl(image.Height) / divideByH)
End If
Dim scaled As New Bitmap(width, height)
Dim g As Graphics
g = Graphics.FromImage(scaled)
g.DrawImage(image, New Rectangle(0, 0, width, height), New Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel)
g.Dispose()
ResizedImage = scaled
Else
ResizedImage = image
End If
End Function
来源:https://stackoverflow.com/questions/669137/resize-images-in-windows-mobile