将图像保存到本地路径时出错

时间:2013-06-19 07:44:59

标签: c# asp.net image resize

我得到一个图像文件,重新调整大小,然后在同一文件夹中保存另一个名称(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;
}

我想知道如何修复它?

10 个答案:

答案 0 :(得分:6)

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

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;
}

答案 1 :(得分: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;

答案 2 :(得分:1)

这似乎是一个许可问题。

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

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

答案 3 :(得分:1)

我认为您应该检查您的写入文件的权限,因为我找不到您的代码中的任何重大问题。

答案 4 :(得分: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); 

答案 5 :(得分:1)

我做了一些更改,这段代码运行正常:(在重新调整大小之前,您必须先将文件上传到您的网站。重新调整大小后,您可以删除原始文件) 第1步:我已将Image复制到我的应用程序中。 第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);
    }

答案 6 :(得分: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);
    }

答案 7 :(得分:1)

答案 8 :(得分: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)
        {

        }
    }
}

答案 9 :(得分:1)

关于这一行:

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

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