5

我得到一个图像文件,重新调整它的大小,然后在同一个文件夹中以不同的名称保存( filename+"-resize" ),但是我收到了这个错误

A generic error occurred in GDI+

这是我调整大小方法的代码,

private  string resizeImageAndSave(string imagePath)
{
    System.Drawing.Image fullSizeImg
         = System.Drawing.Image.FromFile(Server.MapPath(imagePath));
    var thumbnailImg = new Bitmap(565, 290);
    var thumbGraph = Graphics.FromImage(thumbnailImg);
    thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
    thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
    thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
    var imageRectangle = new Rectangle(0, 0, 565, 290);
    thumbGraph.DrawImage(fullSizeImg, imageRectangle);
    string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath),     Path.GetFileNameWithoutExtension(imagePath) + "-resize");
    thumbnailImg.Save(targetPath, ImageFormat.Jpeg); //(A generic error occurred in GDI+) Error occur here !
    thumbnailImg.Dispose();
    return targetPath;
}

我想知道如何解决它?

4

10 回答 10

7

正如其他人所说,这可能是权限问题或目录可能不存在。但是,您可以在保存之前尝试克隆图像。如果上述不是问题,这可以解决问题。

private static string resizeImageAndSave(string imagePath)
{
    System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(Server.MapPath(imagePath));
    var thumbnailImg = new Bitmap(565, 290);
    var thumbGraph = Graphics.FromImage(thumbnailImg);
    thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
    thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
    thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
    var imageRectangle = new Rectangle(0, 0, 565, 290);
    thumbGraph.DrawImage(fullSizeImg, imageRectangle);
    fullSizeImg.Dispose(); //Dispose of the original image
    string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath), Path.GetFileNameWithoutExtension(imagePath) + "-resize");
    Bitmap temp = thumbnailImg.Clone() as Bitmap; //Cloning
    thumbnailImg.Dispose();
    temp.Save(targetPath, ImageFormat.Jpeg); 
    temp.Dispose();
    return targetPath;
}
于 2013-06-25T16:13:36.320 回答
4

在这行代码之后...

string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath),     Path.GetFileNameWithoutExtension(imagePath) + "-resize");

请试试这个...添加带有扩展名的图像名称

if (!Directory.Exists(targetPath))
   Directory.CreateDirectory(targetPath);
//now do the rest and place image name and extension...
thumbnailImg.Save(targetPath + @"\img.jpg", ImageFormat.Jpeg); 
thumbnailImg.Dispose();
return targetPath;
于 2013-06-27T02:47:20.377 回答
1

这似乎是一个权限问题。

更改目标文件夹上的权限,以便 ASP.NET 可以写入该文件夹。

请记住,保存文件的用户不是您,而是 ASP.NET 用户。

于 2013-06-21T08:17:01.320 回答
1

我认为你应该检查你写文件的许可,因为我从你的代码中找不到任何大问题。

于 2013-06-21T08:18:13.170 回答
1

请检查正在构建的路径是什么,您可以在保存之前使用以下内容以确保您的目录路径存在:-

Directory.CreateDirectory(Path.GetDirectoryName(fileName));

还要考虑源文件上的问题锁定,因此您可以创建副本并处理现有参考:-

var thumbnailImgNew = new Bitmap(thumbnailImg);
thumbnailImg.Dispose(); 
thumbnailImg=null;
//Save it to target path
thumbnailImgNew.Save(targetPath, ImageFormat.Jpeg); 
于 2013-06-24T06:41:53.973 回答
1

我做了一些更改,这段代码工作正常:(在重新调整大小之前,您必须先将文件上传到您的网站。重新调整大小后,您可以删除原始文件) 第 1 步:我已将图像复制到我的应用程序中。第 2 步:在按钮单击事件中,我已检索图像路径并提供给重新调整大小功能。

private string resizeImageAndSave(string imagePath)
    {
        System.Drawing.Image fullSizeImg
             = System.Drawing.Image.FromFile(imagePath);
        var thumbnailImg = new Bitmap(565, 290);
        var thumbGraph = Graphics.FromImage(thumbnailImg);
        thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
        thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
        thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
        var imageRectangle = new Rectangle(0, 0, 565, 290);
        thumbGraph.DrawImage(fullSizeImg, imageRectangle);
        string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath), Path.GetFileNameWithoutExtension(imagePath) + "-resize");
        thumbnailImg.Save(targetPath, ImageFormat.Jpeg); //(A generic error occurred in GDI+) Error occur here !
        thumbnailImg.Dispose();
        return targetPath;
    }
    protected void bntUploadFile_Click(object sender, EventArgs e)
    {
        string file = Server.MapPath("tree.jpg");
        resizeImageAndSave(file);
    }
于 2013-06-25T05:08:27.987 回答
1

试试这个代码:

    private string resizeImageAndSave(byte[] imageBytes, string fileName) {
        var mem = new MemoryStream(imageBytes);
        System.Drawing.Image fullSizeImg = System.Drawing.Image.FromStream(mem);

        var thumbnailImg = new Bitmap(565, 290);
        var thumbGraph = Graphics.FromImage(thumbnailImg);
        thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
        thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
        thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

        var imageRectangle = new Rectangle(0, 0, 565, 290);
        thumbGraph.DrawImage(fullSizeImg, imageRectangle);

        string targetPath = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileNameWithoutExtension(fileName) + "-resize.jpg");

        thumbnailImg.Save(targetPath, ImageFormat.Jpeg); //(A generic error occurred in GDI+) Error occur here !
        thumbnailImg.Dispose();

        return targetPath;
    }

    protected void SaveButton_Click(object sender, EventArgs e) {
        var inStream = Request.Files[0].InputStream;
        var buff = new byte[inStream.Length];

        inStream.Read(buff, 0, buff.Length);

        resizeImageAndSave(buff, Request.Files[0].FileName);
    }
于 2013-06-27T09:27:38.910 回答
1

我认为该链接可以帮助您

http://www.codeproject.com/Articles/23011/Simple-Image-Resizing-Library

于 2013-06-27T20:31:41.867 回答
1

问题不在于位置,问题在于调整大小。

调整大小、裁剪图像时可能会出现 GDI 问题。确保您的图像将是 100% 的矩形大小,或者将您的图像裁剪为所需的大小,然后调整它的大小。

因此,如果您有 800x600 的图像并且您想将其调整为 450x339,您将有一个空像素,这可能会导致 GDI+ 出错,所以我建议您确保调整大小时的图像具有正确的大小。因此,如果这可以帮助您,我创建了可以帮助我调整图像大小和裁剪图像的类。

public class ImageHandler
{
    private Image cropImage(Image img, Rectangle cropArea)
    {
        Bitmap bmpImage = new Bitmap(img);
        if (bmpImage.Size.Width < cropArea.Width)
            cropArea.Width = bmpImage.Size.Width;
        if (bmpImage.Size.Height < cropArea.Height)
            cropArea.Height = bmpImage.Size.Height;
        Bitmap bmpCrop = bmpImage.Clone(cropArea,
                                        bmpImage.PixelFormat);
        return (Image)(bmpCrop);
    }

    private Image resizeImage(Image imgToResize, Size size)
    {
        int sourceWidth = imgToResize.Width;
        int sourceHeight = imgToResize.Height;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)size.Width / (float)sourceWidth);
        nPercentH = ((float)size.Height / (float)sourceHeight);

        if (nPercentH < nPercentW)
            nPercent = nPercentH;
        else
            nPercent = nPercentW;

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap b = new Bitmap(destWidth, destHeight);
        Graphics g = Graphics.FromImage((Image)b);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
        g.Dispose();

        return (Image)b;
    }
    public Image ResizeWithCrop(Image imgToResize, Size size, bool center = true)
    {
        int sourceWidth = imgToResize.Width;
        int sourceHeight = imgToResize.Height;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)size.Width / (float)sourceWidth);
        nPercentH = ((float)size.Height / (float)sourceHeight);

        if (nPercentH < nPercentW)
            nPercent = nPercentW;
        else
            nPercent = nPercentH;
        float resultWidth = sourceWidth * nPercent;
        float resultHeight = sourceHeight * nPercent;
        int destWidth = (int)resultWidth;
        int destHeight = (int)resultHeight;
        Bitmap b = new Bitmap(destWidth, destHeight);
        Graphics g = Graphics.FromImage((Image)b);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
        g.Dispose();
        int restWidth = destWidth - size.Width;
        int restHeight = destHeight - size.Height;

        int pX = center ? restWidth > 0 ? (int)(restWidth / 2) : 0 : 0;
        int pY = center ? restHeight > 0 ? (int)(restHeight / 2) : 0 : 0;
        return cropImage((Image)b, new Rectangle(pX, pY, size.Width, size.Height));


    }
    public void SaveJpeg(string path, Image img, long quality = 85L)
    {
        try
        {


        EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

        ImageCodecInfo jpegCodec = getEncoderInfo(@"image/jpeg");

        EncoderParameters encoderParams
        = new EncoderParameters(1);

        encoderParams.Param[0] = qualityParam;

        System.IO.MemoryStream mss = new System.IO.MemoryStream();

        System.IO.FileStream fs
        = new System.IO.FileStream(path, System.IO.FileMode.Create
        , System.IO.FileAccess.ReadWrite);

        img.Save(mss, jpegCodec, encoderParams);
        byte[] matriz = mss.ToArray();
        fs.Write(matriz, 0, matriz.Length);

        mss.Close();
        fs.Close();
        }
        catch (Exception ex)
        {

        }
    }

    private ImageCodecInfo getEncoderInfo(string mimeType)
    {
        // Get image codecs for all image formats
        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

        // Find the correct image codec
        for (int i = 0; i < codecs.Length; i++)
            if (codecs[i].MimeType == mimeType)
                return codecs[i];
        return null;
    }

    public void SavePng(string path, Image img, long quality = 85L)
    {
        try
        {
            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

            ImageCodecInfo jpegCodec = getEncoderInfo(@"image/png");

            EncoderParameters encoderParams
            = new EncoderParameters(1);

            encoderParams.Param[0] = qualityParam;

            System.IO.MemoryStream mss = new System.IO.MemoryStream();

            System.IO.FileStream fs
            = new System.IO.FileStream(path, System.IO.FileMode.Create
            , System.IO.FileAccess.ReadWrite);

            img.Save(mss, jpegCodec, encoderParams);
            byte[] matriz = mss.ToArray();
            fs.Write(matriz, 0, matriz.Length);

            mss.Close();
            fs.Close();
        }
        catch (Exception ex)
        {

        }
    }
}
于 2013-06-27T20:37:35.467 回答
1

关于这一行:

string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath),     Path.GetFileNameWithoutExtension(imagePath) + "-resize");

您确定原始 imagePath 中没有多次出现不带扩展名的文件名吗?这可能会导致问题,例如没有针对正确的文件夹。

于 2013-06-28T05:13:21.880 回答