重新调整大小并将图像保存到数据库

时间:2012-01-20 11:56:34

标签: c# sql-server asp.net-mvc image-upload

解决了下面的第一个问题,但我仍然需要能够重新调整/重新调整我的代码在将物理文件保存到服务器时所执行的操作。现在已经过去了 存储在数据库中它不起作用..

我在我的代码中看到我没有将重新缩放的图像传递给InputStream,我正在传入原始文件库..可以以某种方式传递newImage作为其不同类型..?

我在从数据库存储/检索图像时遇到了麻烦。最初我有代码允许上传图像,调整大小到所需的尺寸并存储为物理文件。但现在我需要将图像保存到数据库(MS SQL)。

我正在使用MVC2 .NET 3.5

我的代码是一些混搭的不同图片上传对我来说很简单:)

这是用于上传的控制器:

[HttpPost]
public ActionResult ImageUpload(HttpPostedFileBase fileBase, PhotoViewModel photoViewModel)
{
    if (photoViewModel.Button == "Upload")
    {
        photoViewModel.ImageValid = "Valid";
        ImageService imageService = new ImageService();

        if (fileBase != null && fileBase.ContentLength > 0 && fileBase.ContentLength <= 2097152 && fileBase.ContentType.Contains("image/"))
        {
            Path.GetExtension(fileBase.ContentType);
            var extension = Path.GetExtension(fileBase.FileName);

            if (extension.ToLower() != ".jpg" && extension.ToLower() != ".gif") // only allow these types
            {
                photoViewModel.ImageValid = "Not Valid";
                ModelState.AddModelError("Photo", "Wrong Image Type");
                return View(photoViewModel);
            }
            EncoderParameters encodingParameters = new EncoderParameters(1);
            encodingParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L); // Set the JPG Quality percentage

            ImageCodecInfo jpgEncoder = imageService.GetEncoderInfo("image/jpeg");
            var uploadedimage = Image.FromStream(fileBase.InputStream, true, true);

            Bitmap originalImage = new Bitmap(uploadedimage);
            Bitmap newImage = new Bitmap(originalImage, 274, 354);

            Graphics g = Graphics.FromImage(newImage);
            g.InterpolationMode = InterpolationMode.HighQualityBilinear;
            g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);

            var streamLarge = new MemoryStream();
            newImage.Save(streamLarge, jpgEncoder, encodingParameters);

            var fileExtension = Path.GetExtension(extension);
            string newname;
            if (photoViewModel.photoURL != null)
            {
                newname = photoViewModel.photoURL;
            }
            else
            {
                newname = Guid.NewGuid() + fileExtension;
            }

            //changed this up now, so it stores the image in db as apposed to physical path
            photoViewModel.photo = newname;
            photoViewModel.ContentType = fileBase.ContentType;
            Int32 length = fileBase.ContentLength;
            byte[] tempImage = new byte[length];
            fileBase.InputStream.Read(tempImage, 0, length);
            photoViewModel.ImageData = tempImage;          

            TempImageUpload tempImageUpload = new TempImageUpload();
            tempImageUpload.TempImageData = tempImage;
            tempImageUpload.ContentType = photoViewModel.ContentType;

            photoViewModel.TempImageId = _service.InsertImageDataBlob(tempImageUpload);

            originalImage.Dispose();
            streamLarge.Dispose();
            return View(photoViewModel);
        }

        if (fileBase != null)
        {
            if (fileBase.ContentLength > 0) ModelState.AddModelError("Photo", "Image size too small");
            if (fileBase.ContentLength <= 2097152) ModelState.AddModelError("Photo", "Image size too big");
            if (fileBase.ContentType.Contains("image/")) ModelState.AddModelError("Photo", "Wrong Image Type");
        }
        else ModelState.AddModelError("Photo", "Please upload a image");

        if (!ModelState.IsValid)
        {
            photoViewModel.ImageValid = "Not Valid";
            return View(photoViewModel);
        }
    }
    return View(photoViewModel);
}

这是我的存储库类:

public int InsertImageDataBlob(TempImageUpload tempImageUpload)
{
  int ReturnedPhotoId;

  try
  {
    var phototempdata = new Photo
             {
                  ImageData = tempImageUpload.TempImageData,
                  contentType = tempImageUpload.ContentType,
                  dateUploaded = DateTime.Now
             };
    _db.Photos.InsertOnSubmit(phototempdata);
    Save();
    ReturnedPhotoId = phototempdata.id;
    return ReturnedPhotoId;
  }
  catch (Exception ex)
  {
    //ErrorLogging;
  }
  return 0;
}

数据库中的图像数据字段(图像类型)将填充数据。

任何帮助都会非常感激,我会逐渐变得灰暗!!

由于

2 个答案:

答案 0 :(得分:1)

可能它的工作原理..或者不是:-P ....我的代码中的绕过/重新缩放问题的更改(查看我的代码中的注释):

[HttpPost]
public ActionResult ImageUpload(HttpPostedFileBase fileBase, PhotoViewModel photoViewModel)
{
    if (photoViewModel.Button == "Upload")
    {
        photoViewModel.ImageValid = "Valid";
        ImageService imageService = new ImageService();

        if (fileBase != null && fileBase.ContentLength > 0 && fileBase.ContentLength <= 2097152 && fileBase.ContentType.Contains("image/"))
        {
            Path.GetExtension(fileBase.ContentType);
            var extension = Path.GetExtension(fileBase.FileName);

            if (extension.ToLower() != ".jpg" && extension.ToLower() != ".gif") // only allow these types
            {
                photoViewModel.ImageValid = "Not Valid";
                ModelState.AddModelError("Photo", "Wrong Image Type");
                return View(photoViewModel);
            }
            EncoderParameters encodingParameters = new EncoderParameters(1);
            encodingParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L); // Set the JPG Quality percentage

            ImageCodecInfo jpgEncoder = imageService.GetEncoderInfo("image/jpeg");
            var uploadedimage = Image.FromStream(fileBase.InputStream, true, true);

            Bitmap originalImage = new Bitmap(uploadedimage);
            Bitmap newImage = new Bitmap(originalImage, 274, 354);

            Graphics g = Graphics.FromImage(newImage);
            g.InterpolationMode = InterpolationMode.HighQualityBilinear;
            // change from originalImage to newImage
            g.DrawImage(newImage, 0, 0, newImage.Width, newImage.Height);

            var streamLarge = new MemoryStream();
            newImage.Save(streamLarge, jpgEncoder, encodingParameters);

            var fileExtension = Path.GetExtension(extension);
            string newname;
            if (photoViewModel.photoURL != null)
            {
                newname = photoViewModel.photoURL;
            }
            else
            {
                newname = Guid.NewGuid() + fileExtension;
            }

            //changed this up now, so it stores the image in db as apposed to physical path
            photoViewModel.photo = newname;
            photoViewModel.ContentType = fileBase.ContentType;
            // using the memoryStream streamLarge
            // old code: Int32 length = fileBase.ContentLength;         
            byte[] tempImage = new byte[streamLarge.Length];
            // replace fileBase.InputStream with streamLarge
            streamLarge.Read(tempImage, 0, length);
            photoViewModel.ImageData = tempImage;          

            TempImageUpload tempImageUpload = new TempImageUpload();
            tempImageUpload.TempImageData = tempImage;
            tempImageUpload.ContentType = photoViewModel.ContentType;

            photoViewModel.TempImageId = _service.InsertImageDataBlob(tempImageUpload);

            originalImage.Dispose();
            streamLarge.Dispose();
            return View(photoViewModel);
        }

        if (fileBase != null)
        {
            if (fileBase.ContentLength > 0) ModelState.AddModelError("Photo", "Image size too small");
            if (fileBase.ContentLength <= 2097152) ModelState.AddModelError("Photo", "Image size too big");
            if (fileBase.ContentType.Contains("image/")) ModelState.AddModelError("Photo", "Wrong Image Type");
        }
        else ModelState.AddModelError("Photo", "Please upload a image");

        if (!ModelState.IsValid)
        {
            photoViewModel.ImageValid = "Not Valid";
            return View(photoViewModel);
        }
    }
    return View(photoViewModel);
}

答案 1 :(得分:1)

我实际上已经使用了这段代码:

      photoViewModel.photo = newname;
      photoViewModel.ContentType = fileBase.ContentType;
      streamLarge.Position = 0;
      byte[] tempImage = new byte[streamLarge.Length + 1];
      streamLarge.Read(tempImage, 0, tempImage.Length);
      photoViewModel.ImageData = tempImage;