1

经过搜索,我发现了这段代码:

Public Sub ResizeImage(ByVal scaleFactor As Double, ByVal fromStream As Stream, ByVal toStream As Stream)
    Dim image__1 = System.Drawing.Image.FromStream(fromStream)
    Dim newWidth = CInt(image__1.Width * scaleFactor)
    Dim newHeight = CInt(image__1.Height * scaleFactor)
    Dim thumbnailBitmap = New System.Drawing.Bitmap(newWidth, newHeight)

    Dim thumbnailGraph = System.Drawing.Graphics.FromImage(thumbnailBitmap)
    thumbnailGraph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
    thumbnailGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
    thumbnailGraph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic

    Dim imageRectangle = New System.Drawing.Rectangle(0, 0, newWidth, newHeight)
    thumbnailGraph.DrawImage(image__1, imageRectangle)
    thumbnailBitmap.Save(toStream, image__1.RawFormat)

    thumbnailGraph.Dispose()
    thumbnailBitmap.Dispose()
    image__1.Dispose()
End Sub

有两件事我无法“修改”来解决我的问题:

  1. 我不想传递流,但我更喜欢传递C:\mysite\photo\myphoto.gif. 如何“转换”它以接受文件而不是流?
  2. 在这个函数中,我必须传递一个“比例”值。但我更喜欢检查图像是否太大(例如 > 1024x768)而不是将其调整为最大1024x768. 我怎样才能用System.Drawing.

如您所见,我对 System.Drawing 一无所知,因此我需要“硬”帮助来解决这项工作。

4

2 回答 2

0

第一个问题:

将 newImage 调暗为 Image = Image.FromFile("SampImag.jpg")

第二个问题:

构建一个私有方法,它将根据给定图像的原始 Size 对象返回一个 Size 对象。如果您愿意,也可以添加“保持比例”标志。

于 2010-06-28T15:25:46.053 回答
0

这是c#我大约 5 年前为执行此操作而编写的一些代码(我希望它仍然可以工作,因为该应用程序从那时起就没有被触及)。我认为它可以满足您的所有需求,但如果图像较小,它不会将图像放大到 1024x768。此代码只会确保如果它大于 1024x768,它将按比例调整大小以适应这些尺寸:

const int maxWidth = 1024;
const int maxHeight = 768;
Image newImage = Image.FromFile("YourPicture.jpg");
double percentToShrink = -1;
if (newImage.Width >= newImage.Height)
{
    // Do we need to resize based on width?
    if (newImage.Width > maxWidth)
    {
        percentToShrink = (double)maxWidth / (double)newImage.Width;
    }
}
else
{
    // Do we need to resize based on width?
    if (newImage.Height > maxHeight )
    {
        percentToShrink = (double)maxHeight  / (double)newImage.Height;
    }
}

int newWidth = newImage.Width;
int newHeight = newImage.Height;

// So do we need to resize?
if (percentToShrink != -1)
{
    newWidth = (int)(newImage.Width * percentToShrink);
    newHeight = (int)(newImage.Height * percentToShrink);
}

// convert the image to a png and get a byte[]
MemoryStream imgStream = new MemoryStream();
Bitmap bmp = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(bmp))
{
    g.InterpolationMode =   System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
    g.FillRectangle(System.Drawing.Brushes.White, 0, 0, newWidth, newHeight);
    g.DrawImage(newImage, 0, 0, newWidth, newHeight);
}

// This can be whatever format you need
bmp.Save(imgStream, System.Drawing.Imaging.ImageFormat.Png);
byte[] imgBinaryData = imgStream.ToArray();
imgStream.Dispose();

如果您需要将其转换为 VB.NET,您可以在此处使用 C# 到 VB.NET 转换器。

于 2010-06-28T15:46:21.503 回答