Ir para conteúdo
Fórum Script Brasil
  • 0

Cropper(cortar) de imagem com asp+javascript+freeaspupload


Jonathan Cardozo

Pergunta

Utilizando umas bibliotecas prontas de javascript(baixei o pacote da web) e o freeaspupload em conjunto com o aspimage/aspjpeg criei o esquema tipo o orkut, deixando o usuario escolher a área da imagem que deseja recortar e criar a miniatura(thumb).

Vejam o exemplo: http://www.allmarketweb.com/jonathandj/exemplos/cropper/

Download do material completo: http://www.allmarketweb.com/jonathandj/cod...na=1&ordem=

Abaixo uma parte do código asp pra ver quem se anima:

*****Página popupResize.asp
<%
option explicit
%>
<!-- #include file="classes/clsImagem.asp" -->
<%
if Request.ServerVariables("REQUEST_METHOD") = "POST" then
 dim x
 set x = new clsImage
 x.imagePath = Server.MapPath(".")&"\imagens\" 'imagem já redimensionada
 x.tempPath = Server.MapPath(".")&"\imagens\" 'imagem já redimensionada
 x.originalNameFile = Request.Form("renameFile") 'nome do arquivo redimensionado
 x.cropH = Request.form("height") 'altura da seleção
 x.cropW = Request.form("width") 'largura da seleção
 x.cropX = Request.form("x1") 'ponto X de início da seleção
 x.cropY = Request.form("y1") 'ponto Y de início da seleção
 x.createThumb = true 'habilita o thumb
 x.thumbAuto = false 'desabilita o thumb automatico para ser criado o thumb de seleção
 x.resizeImage
 set x = nothing
 response.write "<script>"&_
 " opener.location='default.asp?preview="&Request.Form("renameFile")&"';"&_
 " window.close();"&_
 "</script>"
 response.end
end if
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
 <meta http-equiv="Content-Language" content="en-us" />
 <title></title> 

 <script src="lib/prototype.js" type="text/javascript"></script> 
 <script src="lib/scriptaculous.js?load=builder,dragdrop" type="text/javascript"></script>
 <script src="cropper.js" type="text/javascript"></script> 

 <script type="text/javascript" charset="utf-8">

 function onEndCrop( coords, dimensions ) {
 $( 'x1' ).value = coords.x1;
 $( 'y1' ).value = coords.y1;
 $( 'x2' ).value = coords.x2;
 $( 'y2' ).value = coords.y2;
 $( 'width' ).value = dimensions.width;
 $( 'height' ).value = dimensions.height;

 }

 // with a supplied ratio
 Event.observe( 
 window, 
 'load', 
 function() { 
 new Cropper.Img( 
 'testImage', 
 { 
 minWidth: 117, 
 minHeight: 83, 
 ratioDim: { x: 117, y: 83 }, 
 displayOnInit: true, 
 onEndCrop: onEndCrop 
 } 
 ) 
 } 
 );

 </script>
 <link rel="stylesheet" type="text/css" href="debug.css" media="all" />
 <style type="text/css">
 label { 
 clear: left;
 margin-left: 50px;
 float: left;
 width: 5em;
 }

 #testWrap {
 margin: 20px 0 0 50px; /* Just while testing, to make sure we return the correct positions for the image & not the window */
 }
 </style>
</head>
<body style="padding:0px;margin:0px;"> 
 <div id="testWrap" style="padding:0px;margin:0px;" align="center">
 <img src="imagens/<%=request.QueryString("file")%>" id="testImage" />
 </div> 
 <form name="form1" action="popupResize.asp" method="post" style="padding:0px;margin:0px;">
 <input type="hidden" value="<%=request.QueryString("file")%>" name="renameFile" />
 <input type="hidden" name="x1" id="x1" />
 <input type="hidden" name="y1" id="y1" />
 <input type="hidden" name="x2" id="x2" />
 <input type="hidden" name="y2" id="y2" />
 <input type="hidden" name="width" id="width" />
 <input type="hidden" name="height" id="height" />
 <center>
 <input type="submit" name="submit" value="Salvar" />
 </center>
 </form> 
</body>
</html>

*****************************************************************
*****************************************************************
*****************************************************************
*****************************************************************
****Página default.asp
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
option explicit
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function popup(imagem,wdh,hgt){
 posL = screen.availWidth/2 - wdh/2;
 posT = screen.availHeight/2 - hgt/2;
 str = 'width='+wdh+', height='+hgt+', left='+posL+', top='+posT+', scrollbars=no';
 window.open('popupResize.asp?file='+ imagem, '', str);
}
</script>
</head>

<body>
<!-- #include file="classes/freeaspupload.asp" -->
<!-- #include file="classes/clsImagem.asp" -->
<%
if Request.ServerVariables("REQUEST_METHOD") = "POST" then
 dim Upload, f
 dim originalNameFile, renameFile, thumbAuto, createThumb, x

 Set Upload = New FreeASPUpload
 'faz o upload da imagem para a pasta temporária
 Upload.Save(Server.MapPath(".")&"\imagens\temp\")
 'originalNameFile = Upload.UploadedFiles("imagem").FileName
 thumbAuto = upload.form("thumbAuto")
 For Each f In upload.UploadedFiles.Items

 originalNameFile = f.FileName


 'define o novo nome do arquivo
 renameFile = Session.SessionID & ".jpg"&f.ext

 set x = new clsImage
 'verifica se é ou não para criar o thumb automatico
 if thumbAuto="1" then
 thumbAuto = false
 createThumb = false
 else
 thumbAuto = true
 createThumb = true
 end if
 'força o redimensionamento da imagem principal e salva na pasta 
 x.originalNameFile = originalNameFile
 x.imagePath = Server.MapPath(".")&"\imagens\"
 x.newNameFile = renameFile
 x.createThumb = createThumb
 x.thumbAuto = thumbAuto
 x.resizeImage
 set x = nothing

 set x = new clsImage
 'força o redimensionamento da imagem principal e salva na pasta com nova dimensão
 x.originalNameFile = renameFile
 x.imagePath = Server.MapPath(".")&"\imagens\150X100\"
 x.tempPath = Server.MapPath(".")&"\imagens\"
 x.newNameFile = renameFile
 x.maxH = 150
 x.maxW = 100
 x.createThumb = false
 x.thumbAuto = false
 x.deleteOriginalFile = false
 x.resizeImage
 set x = nothing 

 if thumbAuto = false then
 Response.Write("<script>popup('"&renameFile&"',680,550);</script>")
 Response.End()
 else
 response.write "<script>"&_
 " window.location='default.asp?preview="&renameFile&"';"&_
 "</script>"
 Response.End() 
 end if

 next 
 set Upload = nothing
end if
%>
<form action="default.asp" method="post" enctype="multipart/form-data" name="form1" id="form1">
 Selecione a imagem desejada<br />
 <input type="file" name="imagem" id="imagem" />
 <br />
 <input name="thumbAuto" type="checkbox" id="thumbAuto" value="1" />
 Personalizar thumb<br />
 <input type="submit" name="Enviar" id="Enviar" value="Enviar" />
 <br />
</form>
<%
if Request.QueryString("preview")<>"" then
%>
Imagem Redimensionada:
<br />
<img src="imagens/<%=Request.QueryString("preview")%>" />
<br />
Imagem Thumb:
<br />
<img src="imagens/thumb/<%=Request.QueryString("preview")%>" />
<%
end if
%>
</body>
</html>

Link para o comentário
Compartilhar em outros sites

2 respostass a esta questão

Posts Recomendados

  • 0

Ainda bem que existem pessoas dispostas a compartilhar conhecimentos.

excelente código. Já testei e está funcionando quase 100% para o que eu preciso.

Minha dúvida é: como eu altero a proporção quando eu estou selecionando a parte da imagem que irá gerar o tumb.... pois nos meus testes não funciona a seleção só vertical ou só horizontal, o que ta funcionando é só o redimencionamento proporcional fixo da área.

Gostaria de saber onde altero no código para gerar um tumb com características que eu possa modificar, tipo: 100p largura x 30p altura ?

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152k
    • Posts
      651,8k
×
×
  • Criar Novo...