sexta-feira, 24 de julho de 2015

UploadUtils

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Web;

namespace Lapuinka.Web
{
    public class UploadUtils
    {
        public static string SavePostedFile(string path, HttpPostedFileBase file, bool useTimestampInPath)
        {
            if (useTimestampInPath)
            {
                path = Path.Combine(path, DateTime.Now.ToString("yyyyMMddHHmmss"));
            }

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var filename = Path.GetFileName(file.FileName) ?? file.FileName;

            var caminho = Path.Combine(path, filename);

            file.SaveAs(caminho);

            return caminho;
        }

        public static string SavePostedImage(string path, HttpPostedFileBase file, string filename, bool useTimestampInPath, int width, int height)
        {
            if (useTimestampInPath)
            {
                path = Path.Combine(path, DateTime.Now.ToString("yyyyMMddHHmmss"));
            }

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var fname = filename != null ? filename : Path.GetFileNameWithoutExtension(file.FileName) ?? file.FileName;
            fname += ".png";

            var caminho = Path.Combine(path, fname);
           
            var newImage = new Bitmap(150, 150);
            using (Graphics gr = Graphics.FromImage(newImage))
            {
                var srcImage = Image.FromStream(file.InputStream);

                gr.SmoothingMode = SmoothingMode.AntiAlias;
                gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
                gr.DrawImage(srcImage, new Rectangle(0, 0, 150, 150));
            }

            newImage.Save(caminho, ImageFormat.Png);

            return caminho;
        }
    }
}


Postar um comentário