1

我尝试使用此代码调整图像大小:

 ConvertToBitmap(txtImage.Text);

    private void ConvertToBitmap(string filename)
    {
        if (File.Exists(filename))
        {
            var origImg = System.Drawing.Image.FromFile(filename);
            var widthDivisor = (double)origImg.Width / (double)900;
            var heightDivisor = (double)origImg.Height / (double)750;
            int newWidth, newHeight;

            if (widthDivisor < heightDivisor)
            {
                newWidth = (int)((double)origImg.Width / widthDivisor);
                newHeight = (int)((double)origImg.Height / widthDivisor);
            }
            else
            {
                newWidth = (int)((double)origImg.Width / heightDivisor);
                newHeight = (int)((double)origImg.Height / heightDivisor);
            }

            var newImg = new Bitmap(newWidth, newHeight);
            Graphics g = Graphics.FromImage(newImg);
            g.DrawImage(origImg, new Rectangle(0, 0, newWidth, newHeight));
            System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
            encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)350);
            newImg.Save(fullpath, GetImageCodeInfo("image/jpeg"), encoderParameters);
            g.Dispose();
        }
    }

    public static ImageCodecInfo GetImageCodeInfo(string mimeType)
    {
        ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
        foreach (ImageCodecInfo ici in info)
            if (ici.MimeType.Equals(mimeType, StringComparison.OrdinalIgnoreCase))
                return ici;
        return null;
    }

    private ImageCodecInfo GetEncoder(ImageFormat format)
    {

        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

        foreach (ImageCodecInfo codec in codecs)
        {
            if (codec.FormatID == format.Guid)
            {
                return codec;
            }
        }
        return null;
    }

它是调整图像大小,但有些显示错误a generic error occurred in gdi+。欢迎任何额外的努力。

4

2 回答 2

1

授予文件夹的安全完全权限,然后它工作得很好

于 2012-07-12T07:05:42.060 回答
0

请注意发生错误时的私有内存使用情况。由于内存泄漏,也可能会出现此问题。

我看到代码正在处理应在使用后正确处理的图形和其他绘图对象。

循环运行此方法,以查看内存消耗是否急剧增加。如果是,则存在内存泄漏,您必须深入挖掘以找到使用后未处理的对象。

于 2012-07-12T08:39:01.447 回答