Neste artigo vamos demonstrar como fazer o upload de uma imagem, como tratar esse procedimento e como redimensionar as imagens para diversos tamanhos: original, grande e pequeno.
Para fazer o upload de uma imagem, vamos primeiro criar um novo projeto no Visual Studio. Será uma página Default.aspx. Vamos adicionar os componentes FileUpload, Button e Label, conforme mostra a Figura 1.
A codificação desses componentes está presente na Listagem 1.
Listagem 1. Codificação da página Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<div>
<div id="content">
<form id="form2" runat="server">
<div>
<br />
<asp:FileUpload ID="FileUploadControl" runat="server"
class="multi" AllowMultiple="True" />
<br />
<asp:Label runat="server" id="StatusLabel" text=""
ForeColor="Red" />
<br />
<asp:Button ID="btnUpload" runat="server" Text=" Carregar Fotos "
onclick="btnUpload_Click" BackColor="#CC0000" BorderColor="#CC0000"
Font-Bold="True" ForeColor="White" />
<br /> <br />
</div>
</form>
<br class="clearfix" />
</div>
</div>
</body>
</html>
Depois do projeto pronto, dê um duplo clique no botão "Carregar Foto" para abrir o code behind Default.aspx.cs, conforme mostra a Figura 2.
Em seguida, adicione o código da função, conforme mostra a Listagem 2. Repare que todo o código está comentado para facilitar o aprendizado.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUploadControl.PostedFile.ContentLength < 8388608)
{
try
{
if (FileUploadControl.HasFile)
{
try
{
//Aqui ele vai filtrar pelo tipo de arquivo
if (FileUploadControl.PostedFile.ContentType == "image/jpeg" ||
FileUploadControl.PostedFile.ContentType == "image/png" ||
FileUploadControl.PostedFile.ContentType == "image/gif" ||
FileUploadControl.PostedFile.ContentType == "image/bmp")
{
try
{
//Obtem o HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
//Pega o nome do arquivo
string nome = System.IO.Path.GetFileName(hpf.FileName);
//Pega a extensão do arquivo
string extensao = Path.GetExtension(hpf.FileName);
//Gera nome novo do Arquivo numericamente
string filename = string.Format("{0:00000000000000}", GerarID());
//Caminho a onde será salvo
hpf.SaveAs(Server.MapPath("~/uploads/fotos/") + filename + i
+ extensao);
//Prefixo p/ img pequena
var prefixoP = "-p";
//Prefixo p/ img grande
var prefixoG = "-g";
//pega o arquivo já carregado
string pth = Server.MapPath("~/uploads/fotos/")
+ filename + i + extensao;
//Redefine altura e largura da imagem e Salva o arquivo + prefixo
Redefinir.resizeImageAndSave(pth, 70, 53, prefixoP);
Redefinir.resizeImageAndSave(pth, 500, 331, prefixoG);
}
}
}
catch (Exception ex)
{
}
// Mensagem se tudo ocorreu bem
StatusLabel.Text = "Todas imagens carregadas com sucesso!";
}
else
{
// Mensagem notifica que é permitido carregar apenas
// as imagens definida la em cima.
StatusLabel.Text = "É permitido carregar apenas imagens!";
}
}
catch (Exception ex)
{
// Mensagem notifica quando ocorre erros
StatusLabel.Text = "O arquivo não pôde ser carregado.
O seguinte erro ocorreu: " + ex.Message;
}
}
}
catch (Exception ex)
{
// Mensagem notifica quando ocorre erros
StatusLabel.Text = "O arquivo não pôde ser carregado.
O seguinte erro ocorreu: " + ex.Message;
}
}
else
{
// Mensagem notifica quando imagem é superior a 8 MB
StatusLabel.Text = "Não é permitido carregar mais do que 8 MB";
}
}
Agora adicione uma função chamada de Gera ID. Ela serve para gerar strings numéricas conforme a data e hora para que nunca repita o mesmo ID. Observe a codificação presente na Listagem 3.
public Int64 GerarID()
{
try
{
DateTime data = new DateTime();
data = DateTime.Now;
string s = data.ToString().Replace("/", "").Replace(":", "").Replace(" ", "");
return Convert.ToInt64(s);
}
catch (Exception erro)
{
throw;
}
}
Pronto! A parte principal da default já foi feita. Agora não podemos nos esquecer de importar a nossa função redefinir.cs para dentro do code behind da nossa página Default.
Agora crie as pastas e a classe redefinir.cs. Veja onde elas ficam no print da Figura 3.
A codificação está presente na Listagem 4.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
namespace UpFoto.Classes
{
public class Redefinir
{
public static string resizeImageAndSave(string imagePath, int largura,
int altura, string prefixo)
{
System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(imagePath);
var thumbnailImg = new Bitmap(largura, altura);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
thumbGraph.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, largura, altura);
thumbGraph.DrawImage(fullSizeImg, imageRectangle);
string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath),
Path.GetFileNameWithoutExtension(imagePath) + prefixo);
thumbnailImg.Save(targetPath, System.Drawing.Imaging.ImageFormat.Jpeg);
thumbnailImg.Dispose();
return targetPath;
}
}
}
Repare no nosso resultado final que a imagem é carregada e mantém a original. A mesma também é redefinida no tamanho escolhido pelo usuário em versões grande e pequena.
Observe como fica o resultado na Figura 4.