Jump to content

POWERED BY:

Archived

This topic is now archived and is closed to further replies.

Lab Design

[Resolvido] Class para redimensionar imagens em c#

Recommended Posts

Mais uma ajuda pra quem precisar.

O método upload talvez nao seja tão importante mas o resize com certeza é.

 

 

using System;

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;

using System.Web;

using System.Web.UI.WebControls;

 

namespace webAdmin

{

 

/// <summary>

/// Faz o upload e sobrepõe se ja existir caso a flagh override eseja true

/// </summary>

public class Images {

 

 

public Boolean upLoad(FormView _formView, string _control, string _path, Boolean _override) {

 

String pathImage = HttpContext.Current.Server.MapPath(_path);

 

FileUpload _upload = (FileUpload)_formView.FindControl(_control);

 

String path = pathImage + _upload.FileName;

 

if(_upload.HasFile)

{

if (!File.Exists(path) || _override) {

// To enable this sample, grant Write permission to the ASP.NET process account

// for the Images subdirectory and uncomment below lines of code.

try {

_upload.SaveAs(path);

return true;

}

catch {

return false;

}

}

}

return false;

}

 

 

 

 

 

/// <summary>

/// Redimensiona imagem

/// scrPath = path da imagem original

/// destPath = path para a nova imagem

/// caso o destPath seja igual ao scrPath, a nova imagem substitui a anterior

/// </summary>

 

public static void Resize(string srcPath, string destPath, int nWidth, int nHeight) {

 

string temp;

// abre arquivo original

System.Drawing.Image img = System.Drawing.Image.FromFile(srcPath);

int oWidth = img.Width; // largura original

int oHeight = img.Height; // altura original

 

// redimensiona se necessario

if(oWidth > nWidth || oHeight > nHeight)

{

 

if(oWidth > oHeight)

{

// imagem horizontal

nHeight = (oHeight * nWidth) / oWidth;

}

else

{

// imagem vertical

nWidth = (oWidth * nHeight) / oHeight;

}

}

 

// cria a copia da imagem

System.Drawing.Image imgThumb = img.GetThumbnailImage(nWidth, nHeight, null, new System.IntPtr(0));

 

if(srcPath == destPath)

{

temp = destPath + ".tmp";

imgThumb.Save(temp, ImageFormat.Jpeg);

img.Dispose();

imgThumb.Dispose();

File.Delete(srcPath); // deleta arquivo original

File.Copy(temp, srcPath); // copia a nova imagem

File.Delete(temp); // deleta temporário

}

else

{

imgThumb.Save(destPath, ImageFormat.Jpeg); // salva nova imagem no destino

imgThumb.Dispose(); // libera memoria

img.Dispose(); // libera memória

}

}

}

}

 

Exemplo de chamada.

1) Esse arquivo Imagem.cs deve ficar na pasta App_Code do projeto ou se preferir, compilar e colocar a dll na pasta bin.

 

 

// faz upload dos arquivos de imagens

// este metodo está code-behind de uma pagina e gerenciamento de arquivos (upload e exclusão)

 

// o manipulador do form chama esse metodo passando o controle com o arquivo uploaded, qual a pasta para ser gravada e se pode sobrepor

//caso já tenha uma cópia na pasta com o mesmo nome.

// o metodo verifica se existe um arquivo no controle

// verifica se o tipo de arquivo é valido e se for, grava na pasta.

// Eu tenho uma pasta no provedor chamada thumbs e caso no metodo o nome da pasta seja a de thumbs

// é chamado o class para redimensionar a imagem neste caso, width máximo 100px e height máximo 100px

// o class verifica o formato da imagem, se horizontal ou vertical

// por exemplo se a imagem for horizontal, o width será 100px e o height proporcional

// se a imagem for vertical, o heigth assume 100px e o width proporcional porém não ultrapassando o limite de 100px.

 

public void upLoadImages(FileUpload upLoadFile, string path, Boolean flash) {

// arquivos imagens do html

if (upLoadFile.HasFile) {

string tipo = upLoadFile.PostedFile.ContentType;

if (tipo == "image/pjpeg" || tipo== "image/gif" || tipo=="image/x-png") {

upLoadFile.SaveAs(path + upLoadFile.FileName);

if (path==thumbsDir) {

//cria thumb DataBind imagem enviada

webAdmin.Images.Resize(path + upLoadFile.FileName, path + upLoadFile.FileName, 100, 100);

}

}

else if (flash && tipo=="application/x-shockwave-flash")

upLoadFile.SaveAs(upLoadFile.FileName);

else

upLoadError.Text = "Arquivo Inválido. Somente arquivos de imagens são permitidos!";

}

}

Share this post


Link to post
Share on other sites

Bem legal a classe, to usando ela...

Até fiz uma mudança no método "Rezide" para não aumentar o tamanho de imagens com tamanho menor que o tamanho definido. se caso for usar pra redimensionar imagens maiores que o tamanho definido e manter as proporções pra imagens menores. As mudanças são bem simples.. ^^

 

Só o método rezide.

public static void Resize(string srcPath, string destPath, int nWidth, int nHeight)
		{

			string temp;
			// abre arquivo original
			System.Drawing.Image img = System.Drawing.Image.FromFile(srcPath);
			int oWidth = img.Width; // largura original
			int oHeight = img.Height; // altura original

			// redimensiona se necessario
			if (oWidth > nWidth || oHeight > nHeight)
			{

				if (oWidth > oHeight)
				{
					// imagem horizontal
					oHeight = (oHeight * nWidth) / oWidth;
					oWidth = 500;
				}
				else
				{
					// imagem vertical
					oWidth = (oWidth * nHeight) / oHeight;
					oHeight = 500;
				}
			}

			// cria a copia da imagem
			System.Drawing.Image imgThumb = img.GetThumbnailImage(oWidth, oHeight, null, new System.IntPtr(0));

			if (srcPath == destPath)
			{
				temp = destPath + ".tmp";
				imgThumb.Save(temp, ImageFormat.Jpeg);
				img.Dispose();
				imgThumb.Dispose();
				File.Delete(srcPath); // deleta arquivo original
				File.Copy(temp, srcPath); // copia a nova imagem
				File.Delete(temp); // deleta temporário
			}
			else
			{
				imgThumb.Save(destPath, ImageFormat.Jpeg); // salva nova imagem no destino
				imgThumb.Dispose(); // libera memoria
				img.Dispose(); // libera memória
			}
		}

Share this post


Link to post
Share on other sites

Olá pessoal, utilizei os métodos e o mesmo fez com que minha imagem tivesse perda de qualidade.

Share this post


Link to post
Share on other sites

Olá pessoal, encontrei uma forma de redimensionar e não perder a qualidade da imagem.

 

Segue abaixo o método

 

 


[font=arial,][color=#000044]public[/color] [color=#000044]void[/color] [color=#0077FF]ResizeImage[/color][color=#444477][b]([/b][/color][color=#000044]string[/color] [color=#0077FF]OriginalFile[/color][color=#444477][b],[/b][/color] [color=#000044]string[/color] [color=#0077FF]NewFile[/color][color=#444477][b],[/b][/color] [color=#000044]int[/color] [color=#0077FF]NewWidth[/color][color=#444477][b],[/b][/color] [color=#000044]int[/color] [color=#0077FF]MaxHeight[/color][color=#444477][b],[/b][/color] [color=#000044]bool[/color] [color=#0077FF]OnlyResizeIfWider[/color][color=#444477][b])[/b][/color][color=#444477][b]{[/b][/color]	[color=#0077FF]System[/color][color=#444477][b].[/b][/color][color=#000044]Drawing[/color][color=#444477][b].[/b][/color][color=#000044]Image[/color] [color=#000044]FullsizeImage[/color] [color=#444477][b]=[/b][/color] [color=#000044]System[/color][color=#444477][b].[/b][/color][color=#000044]Drawing[/color][color=#444477][b].[/b][/color][color=#000044]Image[/color][color=#444477][b].[/b][/color][color=#000044]FromFile[/color][color=#444477][b]([/b][/color][color=#000044]OriginalFile[/color][color=#444477][b]);[/b][/color]	[color=#444477][b]/[/b][/color][color=#BB6666][/color][color=#444477][b]/[/b][/color] [color=#000044]Prevent[/color] [color=#000044]using[/color] [color=#000044]images[/color] [color=#000044]internal[/color] [color=#000044]thumbnail[/color]	[color=#0077FF]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]RotateFlip[/color][color=#444477][b]([/b][/color][color=#000044]System[/color][color=#444477][b].[/b][/color][color=#000044]Drawing[/color][color=#444477][b].[/b][/color][color=#000044]RotateFlipType[/color][color=#444477][b].[/b][/color][color=#000044]Rotate180FlipNone[/color][color=#444477][b]);[/b][/color]	[color=#000044]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]RotateFlip[/color][color=#444477][b]([/b][/color][color=#000044]System[/color][color=#444477][b].[/b][/color][color=#000044]Drawing[/color][color=#444477][b].[/b][/color][color=#000044]RotateFlipType[/color][color=#444477][b].[/b][/color][color=#000044]Rotate180FlipNone[/color][color=#444477][b]);[/b][/color]	[color=#000044]if[/color] [color=#444477][b]([/b][/color][color=#0077FF]OnlyResizeIfWider[/color][color=#444477][b])[/b][/color]	[color=#444477][b]{[/b][/color]		[color=#AA0000][b]if[/b][/color] [color=#444477][b]([/b][/color][color=#0077FF]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Width[/color] [color=#444477][b]<=[/b][/color] [color=#000044]NewWidth[/color][color=#444477][b])[/b][/color]		[color=#444477][b]{[/b][/color]			[color=#000044]NewWidth[/color] [color=#444477][b]=[/b][/color] [color=#000044]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Width[/color][color=#444477][b];[/b][/color]		[color=#444477][b]}[/b][/color]	[color=#444477][b]}[/b][/color]	[color=#000044]int[/color] [color=#0077FF]NewHeight[/color] [color=#444477][b]=[/b][/color] [color=#0077FF]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Height[/color] [color=#444477][b]*[/b][/color] [color=#000044]NewWidth[/color] [color=#444477][b]/[/b][/color] [color=#000044]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Width[/color][color=#444477][b];[/b][/color]	[color=#000044]if[/color] [color=#444477][b]([/b][/color][color=#0077FF]NewHeight[/color] [color=#444477][b]>[/b][/color] [color=#0077FF]MaxHeight[/color][color=#444477][b])[/b][/color]	[color=#444477][b]{[/b][/color]		[color=#444477][b]/[/b][/color][color=#BB6666][/color][color=#444477][b]/[/b][/color] [color=#0077FF]Resize[/color] [color=#000044]with[/color] [color=#000044]height[/color] [color=#000044]instead[/color]		[color=#0077FF]NewWidth[/color] [color=#444477][b]=[/b][/color] [color=#0077FF]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Width[/color] [color=#444477][b]*[/b][/color] [color=#000044]MaxHeight[/color] [color=#444477][b]/[/b][/color] [color=#000044]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Height[/color][color=#444477][b];[/b][/color]		[color=#000044]NewHeight[/color] [color=#444477][b]=[/b][/color] [color=#000044]MaxHeight[/color][color=#444477][b];[/b][/color]	[color=#444477][b]}[/b][/color]	[color=#000044]System[/color][color=#444477][b].[/b][/color][color=#000044]Drawing[/color][color=#444477][b].[/b][/color][color=#000044]Image[/color] [color=#000044]NewImage[/color] [color=#444477][b]=[/b][/color] [color=#000044]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]GetThumbnailImage[/color][color=#444477][b]([/b][/color][color=#000044]NewWidth[/color][color=#444477][b],[/b][/color] [color=#000044]NewHeight[/color][color=#444477][b],[/b][/color] [color=#000044]null[/color][color=#444477][b],[/b][/color] [color=#0077FF]IntPtr[/color][color=#444477][b].[/b][/color][color=#000044]Zero[/color][color=#444477][b]);[/b][/color]	[color=#444477][b]/[/b][/color][color=#BB6666][/color][color=#444477][b]/[/b][/color] [color=#000044]Clear[/color] [color=#000044]handle[/color] [color=#000044]to[/color] [color=#000044]original[/color] [color=#000044]file[/color] [color=#000044]so[/color] [color=#000044]that[/color] [color=#000044]we[/color] [color=#000044]can[/color] [color=#000044]overwrite[/color] [color=#000044]it[/color] [color=#AA0000][b]if[/b][/color] [color=#000044]necessary[/color]	[color=#0077FF]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Dispose[/color][color=#444477][b]();[/b][/color]	[color=#444477][b]/[/b][/color][color=#BB6666][/color][color=#444477][b]/[/b][/color] [color=#000044]Save[/color] [color=#000044]resized[/color] [color=#000044]picture[/color]	[color=#0077FF]NewImage[/color][color=#444477][b].[/b][/color][color=#000044]Save[/color][color=#444477][b]([/b][/color][color=#000044]NewFile[/color][color=#444477][b]);[/b][/color][color=#444477][b]}[/b][/color][/font]

Fonte: http://snippets.dzone.com/posts/show/4336

 

Um grande abraço a todos

Share this post


Link to post
Share on other sites

Olá pessoal, encontrei uma forma de redimensionar e não perder a qualidade da imagem.

 

Segue abaixo o método

 

 


[font=arial,][color=#000044]public[/color] [color=#000044]void[/color] [color=#0077FF]ResizeImage[/color][color=#444477][b]([/b][/color][color=#000044]string[/color] [color=#0077FF]OriginalFile[/color][color=#444477][b],[/b][/color] [color=#000044]string[/color] [color=#0077FF]NewFile[/color][color=#444477][b],[/b][/color] [color=#000044]int[/color] [color=#0077FF]NewWidth[/color][color=#444477][b],[/b][/color] [color=#000044]int[/color] [color=#0077FF]MaxHeight[/color][color=#444477][b],[/b][/color] [color=#000044]bool[/color] [color=#0077FF]OnlyResizeIfWider[/color][color=#444477][b])[/b][/color][color=#444477][b]{[/b][/color]	[color=#0077FF]System[/color][color=#444477][b].[/b][/color][color=#000044]Drawing[/color][color=#444477][b].[/b][/color][color=#000044]Image[/color] [color=#000044]FullsizeImage[/color] [color=#444477][b]=[/b][/color] [color=#000044]System[/color][color=#444477][b].[/b][/color][color=#000044]Drawing[/color][color=#444477][b].[/b][/color][color=#000044]Image[/color][color=#444477][b].[/b][/color][color=#000044]FromFile[/color][color=#444477][b]([/b][/color][color=#000044]OriginalFile[/color][color=#444477][b]);[/b][/color]	[color=#444477][b]/[/b][/color][color=#BB6666][/color][color=#444477][b]/[/b][/color] [color=#000044]Prevent[/color] [color=#000044]using[/color] [color=#000044]images[/color] [color=#000044]internal[/color] [color=#000044]thumbnail[/color]	[color=#0077FF]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]RotateFlip[/color][color=#444477][b]([/b][/color][color=#000044]System[/color][color=#444477][b].[/b][/color][color=#000044]Drawing[/color][color=#444477][b].[/b][/color][color=#000044]RotateFlipType[/color][color=#444477][b].[/b][/color][color=#000044]Rotate180FlipNone[/color][color=#444477][b]);[/b][/color]	[color=#000044]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]RotateFlip[/color][color=#444477][b]([/b][/color][color=#000044]System[/color][color=#444477][b].[/b][/color][color=#000044]Drawing[/color][color=#444477][b].[/b][/color][color=#000044]RotateFlipType[/color][color=#444477][b].[/b][/color][color=#000044]Rotate180FlipNone[/color][color=#444477][b]);[/b][/color]	[color=#000044]if[/color] [color=#444477][b]([/b][/color][color=#0077FF]OnlyResizeIfWider[/color][color=#444477][b])[/b][/color]	[color=#444477][b]{[/b][/color]		[color=#AA0000][b]if[/b][/color] [color=#444477][b]([/b][/color][color=#0077FF]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Width[/color] [color=#444477][b]<=[/b][/color] [color=#000044]NewWidth[/color][color=#444477][b])[/b][/color]		[color=#444477][b]{[/b][/color]			[color=#000044]NewWidth[/color] [color=#444477][b]=[/b][/color] [color=#000044]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Width[/color][color=#444477][b];[/b][/color]		[color=#444477][b]}[/b][/color]	[color=#444477][b]}[/b][/color]	[color=#000044]int[/color] [color=#0077FF]NewHeight[/color] [color=#444477][b]=[/b][/color] [color=#0077FF]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Height[/color] [color=#444477][b]*[/b][/color] [color=#000044]NewWidth[/color] [color=#444477][b]/[/b][/color] [color=#000044]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Width[/color][color=#444477][b];[/b][/color]	[color=#000044]if[/color] [color=#444477][b]([/b][/color][color=#0077FF]NewHeight[/color] [color=#444477][b]>[/b][/color] [color=#0077FF]MaxHeight[/color][color=#444477][b])[/b][/color]	[color=#444477][b]{[/b][/color]		[color=#444477][b]/[/b][/color][color=#BB6666][/color][color=#444477][b]/[/b][/color] [color=#0077FF]Resize[/color] [color=#000044]with[/color] [color=#000044]height[/color] [color=#000044]instead[/color]		[color=#0077FF]NewWidth[/color] [color=#444477][b]=[/b][/color] [color=#0077FF]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Width[/color] [color=#444477][b]*[/b][/color] [color=#000044]MaxHeight[/color] [color=#444477][b]/[/b][/color] [color=#000044]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Height[/color][color=#444477][b];[/b][/color]		[color=#000044]NewHeight[/color] [color=#444477][b]=[/b][/color] [color=#000044]MaxHeight[/color][color=#444477][b];[/b][/color]	[color=#444477][b]}[/b][/color]	[color=#000044]System[/color][color=#444477][b].[/b][/color][color=#000044]Drawing[/color][color=#444477][b].[/b][/color][color=#000044]Image[/color] [color=#000044]NewImage[/color] [color=#444477][b]=[/b][/color] [color=#000044]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]GetThumbnailImage[/color][color=#444477][b]([/b][/color][color=#000044]NewWidth[/color][color=#444477][b],[/b][/color] [color=#000044]NewHeight[/color][color=#444477][b],[/b][/color] [color=#000044]null[/color][color=#444477][b],[/b][/color] [color=#0077FF]IntPtr[/color][color=#444477][b].[/b][/color][color=#000044]Zero[/color][color=#444477][b]);[/b][/color]	[color=#444477][b]/[/b][/color][color=#BB6666][/color][color=#444477][b]/[/b][/color] [color=#000044]Clear[/color] [color=#000044]handle[/color] [color=#000044]to[/color] [color=#000044]original[/color] [color=#000044]file[/color] [color=#000044]so[/color] [color=#000044]that[/color] [color=#000044]we[/color] [color=#000044]can[/color] [color=#000044]overwrite[/color] [color=#000044]it[/color] [color=#AA0000][b]if[/b][/color] [color=#000044]necessary[/color]	[color=#0077FF]FullsizeImage[/color][color=#444477][b].[/b][/color][color=#000044]Dispose[/color][color=#444477][b]();[/b][/color]	[color=#444477][b]/[/b][/color][color=#BB6666][/color][color=#444477][b]/[/b][/color] [color=#000044]Save[/color] [color=#000044]resized[/color] [color=#000044]picture[/color]	[color=#0077FF]NewImage[/color][color=#444477][b].[/b][/color][color=#000044]Save[/color][color=#444477][b]([/b][/color][color=#000044]NewFile[/color][color=#444477][b]);[/b][/color][color=#444477][b]}[/b][/color][/font]

Fonte: http://snippets.dzone.com/posts/show/4336

 

Um grande abraço a todos

 

Oi sublyer, realmente.

Eu percebi isso algum tempo depois que iniciei o post e como por falta de tempo tenho visitado pouco o forum, acabei não reparando nesse detalhe.

Isso é característico do GetThumbnailImage que ao meu ver trabalha com atributos próprios. Eu lembro que corrigi esse detalhe no meu projeto de tratamento de imagens que fazia para um editor de texto. O metodo abaixo funciona perfeitamente:

 

/// <summary>

/// Resize image

/// </summary>

/// <param name="imgToResize"></param>

/// <param name="size"></param>

/// <returns></returns>

public static Image resizeImage(Image imgToResize, Size size)

{

int sourceWidth = imgToResize.Width;

int sourceHeight = imgToResize.Height;

 

float nPercent = 0;

float nPercentW = 0;

float nPercentH = 0;

 

nPercentW = ((float)size.Width / (float)sourceWidth);

nPercentH = ((float)size.Height / (float)sourceHeight);

 

if(nPercentH < nPercentW)

nPercent = nPercentH;

else

nPercent = nPercentW;

 

int destWidth = (int)(sourceWidth * nPercent);

int destHeight = (int)(sourceHeight * nPercent);

 

Bitmap b = new Bitmap(destWidth, destHeight);

Graphics g = Graphics.FromImage((Image)B);

g.InterpolationMode = InterpolationMode.HighQualityBicubic;

 

g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);

g.Dispose();

 

return (Image)b;

}

Share this post


Link to post
Share on other sites

Pessoal estou um problema referente a isso

 

o código funciona certinho, porém quando atualizo uma imagem na grid(troco de imagem) os browser que eu utilizo, mantem a imagem anterior, e só mostra a nova imagem se:

 

no IE se eu deletar os arquivos temporários

e no Firefox se eu Atualizar a pagina

 

alguem pode me ajudar com isso.

 

ja tentei até por código não gerar cache mas não adianta.

Share this post


Link to post
Share on other sites

A pessoal valeu consegui resolver o problema hoje a tarde

 

o que acontecia era que eu tinha uma grid onde eu fazia upload de imagens,

o problema era que tb era possivel sobrescrever esta imagem,

isso acontecia, porém mostrava a imagem velha, então só se eu atualizasse ou apagasse a memória cache

que eu conseguiria ver a nova imagem

 

resolvi este problema add ao page_Load :

 

Response.Expires = 0;

Response.ExpiresAbsolute = DateTime.Now.AddMinutes(-1);

Response.AddHeader("pragma","no-cache");

Response.AddHeader("cache-control","private");

Response.CacheControl = "no-cache";

Response.Cache.SetCacheability(HttpCacheability.NoCache);

 

this.ClearApplicationCache();

 

e criando no mesmo codigo o method para limpar o cache:

 

public void ClearApplicationCache()

{

List<string> keys = new List<string>();

// retrieve application Cache enumerator

IDictionaryEnumerator enumerator = Cache.GetEnumerator();

// copy all keys that currently exist in Cache

while (enumerator.MoveNext())

{

keys.Add(enumerator.Key.ToString());

}

// delete every key from cache

for (int i = 0; i < keys.Count; i++)

{

Cache.Remove(keys);

}

}

 

 

é isso ai pessoal.

Share this post


Link to post
Share on other sites

×

Important Information

Ao usar o fórum, você concorda com nossos Terms of Use.