Asp.net MVC学习日记一(显示图片)

1、在Models文件中建ImageResult类,并继承自ActionResult

   public class ImageResult:ActionResult
    {
        private string _path;
        public ImageResult(string path)
        {
            _path = path;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            byte[] bytes;
            //no context? stop processing
            if (context == null)
                throw new ArgumentNullException("context");
            //check for file
            if (File.Exists(_path)) { bytes = File.ReadAllBytes(_path); }
            else
            {
                throw new FileNotFoundException(_path);
            }

            string contentType = GetContentTypeFromFile();

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = contentType;

            MemoryStream imageStream = new MemoryStream(bytes);
            byte[] buffer = new byte[4096];
            while (true)
            {
                int read = imageStream.Read(buffer, 0, buffer.Length);
                if (read == 0)
                    break;
                response.OutputStream.Write(buffer, 0, read);
            }
            response.End();
        }


        private string GetContentTypeFromFile()
        {
            //get extension from path to determine contentType
            string[] parts = _path.Split('.');
            string extension = Path.GetExtension(_path).Substring(1);
            string contentType;
            switch (extension.ToLower())
            {
                case "jpeg":
                case "jpg":
                    contentType = "image/jpeg";
                    break;
                case "gif":
                    contentType = "image/gif";
                    break;

                default:
                    throw new NotImplementedException(extension + "not handled");
            }
            return contentType;
        }
    }

2、在HomeController.cs文件中添加Action,名称GetImage,并返回ImageResult

        public ImageResult GetImage()
        {
            return new ImageResult(@"C:\Users\Public\Pictures\Sample Pictures\tuyin.jpg");
        }

最后直接访问http://localhost:13811/home/GetImage就可以显示图片了。

 

更进一步指定图片大小显示

1、Models文件夹下新建ImageResizeResult类

 public class ImageResizeResult : ActionResult
    {
        private string _path;
        private int _width;
        private int _maximumHeight;
        private bool _noZooming;

        public ImageResizeResult(string fileName, int width,int maximumHeight, bool noZooming = false)
        {
            //put this path reference in a config file somewhere!
            _path = @"C:\Users\Public\Pictures\Sample Pictures\" + fileName;
            _width = width;
            _maximumHeight = maximumHeight;
            _noZooming = noZooming;
        }

        private ImageFormat GetImageFormatFromFile()
        {
            //get extension from path to determine contentType
            string[] parts = _path.Split('.');
            string extension = parts[parts.Length - 1];
            ImageFormat imageFormat;

            switch (extension.ToLower())
            {
                case "jpeg":
                case "jpg":
                    imageFormat = ImageFormat.Jpeg;
                    break;
                case "gif":
                    imageFormat = ImageFormat.Gif;
                    break;

                default:
                    throw new NotImplementedException(extension + "not handled");
            }
            return imageFormat;
        }

        public Image ResizeImage(string imagePathToResize)
        {
            Image fullsizeImage;
            //check for file
            if (File.Exists(_path))
            {
                fullsizeImage = Image.FromFile(_path);
            }
            else
            {
                throw new FileNotFoundException(_path);
            }
            //load the image from the file system
            fullsizeImage = Image.FromFile(_path);

            // hack to prevent the internal thumbnail from being used!
            fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
            fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);

            // can we zoom this image?
            if (_noZooming)
            {
                if (fullsizeImage.Width <= _width)
                {
                    _width = fullsizeImage.Width;
                }
            }
            // determine new height
            int newHeight = fullsizeImage.Height * _width / fullsizeImage.Width;
            if (newHeight > _maximumHeight)
            {
                // Resize with height instead
                _width = fullsizeImage.Width * _maximumHeight /
                fullsizeImage.Height;
                newHeight = _maximumHeight;
            }

            Image newImage = fullsizeImage.GetThumbnailImage(_width,newHeight, null, IntPtr.Zero);
            //dispose of the in memory original
            fullsizeImage.Dispose();
            return newImage;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            byte[] buffer = new byte[4096];

            HttpResponseBase response = context.HttpContext.Response;
            //no context? stop processing
            if (context == null)
                throw new ArgumentNullException("context");
            //set files content type
            response.ContentType = "image/" +
            GetImageFormatFromFile().ToString();
            //get the resized image
            Image resizedImage = ResizeImage(_path);
            MemoryStream ms = new MemoryStream();
            resizedImage.Save(ms, GetImageFormatFromFile());
            MemoryStream imageStream = new MemoryStream(ms.ToArray());
            while (true)
            {
                int read = imageStream.Read(buffer, 0, buffer.Length);
                if (read == 0)
                    break;
                response.OutputStream.Write(buffer, 0, read);
            }
            response.End();
            ms.Dispose();
            imageStream.Dispose();
        }
    }

 

2、在HomeController.cs文件中添加Action,名称GetImage,并返回ImageResult

        public ImageResizeResult GetImage(string image, int width, int height, bool noZooming = false)
        {
            return new ImageResizeResult(image, width, height, noZooming);
        }

3、在home文件夹中Index.aspx中加上对图片的引用

    <p>
        <img src="/home/GetImage?image=tu.jpg&width=160&height=100"/>
        <img src="/home/GetImage?image=tuyin.jpg&width=75&height=20" />
        <img src="/home/GetImage?image=tuyin.jpg&width=100&height=100&noZooming=true" />
    </p>

最后访问http://localhost:13811/home/ 就可看到效果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

leesmn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值