Asp.net MVC學習日記一(顯示圖片)

來源:互聯網
上載者:User

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/ 就可看到效果

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.