Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Mauricio P. Moura

Imagem diminuida com base na largura

Recommended Posts

Pessoal,

Estou fazendo o cadastro de imagens através de um formulário no qual defino o tamanho da largura que está cadastrada em um banco de dados, e diminuo a imagem com essa largura, diminuindo tb a altura sem desfoca-la.

Já pesquisei em vários forúns e não encontrei.

Tenho instalado o ImageMagick no servidor mas não consegui nada.

 

Alguem poderia me ajudar?

Compartilhar este post


Link para o post
Compartilhar em outros sites

nao necessariamente

 

tipo , eu to usando uma aonde eu peguei na net e so adaptei,

tipo , eles sao assim neh

 

<img src="thumbs.php?img=<diretorio>.<extensão>">

Basta tu colocar outros 'atributos' de envio:

 

<img src="thumbs.php?img=<diretorio>.<extensão>&w=150&h=200">

aonde w é width e h é height.

 

e na pagina thumbs , ao inves de dar o valor , basta tu far um GET["w"] e GET["h"]

 

Abrçs

 

Felipe

Compartilhar este post


Link para o post
Compartilhar em outros sites

nao necessariamente

 

tipo , eu to usando uma aonde eu peguei na net e so adaptei,

tipo , eles sao assim neh

 

<img src="thumbs.php?img=<diretorio>.<extensão>">

Basta tu colocar outros 'atributos' de envio:

 

<img src="thumbs.php?img=<diretorio>.<extensão>&w=150&h=200">

aonde w é width e h é height.

 

e na pagina thumbs , ao inves de dar o valor , basta tu far um GET["w"] e GET["h"]

 

Abrçs

 

Felipe

 

 

Fiz da seguinte forma mas não salva a imagem na pasta:

 

function geraThumb($imagem, $output, $new_width)

{

$source = imagecreatefromstring(file_get_contents($photo));

list($width, $height) = getimagesize($photo);

if ($width>$new_width)

{

$new_height = ($new_width/$width) * $height;

$thumb = imagecreatetruecolor($new_width, $new_height);

imagecopyresampled($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

copy(imagejpeg($thumb, $output, 100),"../arquivos/$pasta/$imagem_salvar");

}

else

{

copy($photo, $output,"../arquivos/$pasta/$imagem_salvar");

}

}

Compartilhar este post


Link para o post
Compartilhar em outros sites

<?php
/**
* Carregamento e redimensionamento de imagens
*/
class Image {
/**
 * Extensão padrão da imagem, caso nenhuma seja fornecida
 */
const DEFAULT_IMG_EXT = "jpg";

/**
 * Qualidade padrão quando formos salvar um jpg
 */
const DEFAULT_IMG_QUALITY = 75;

/**
 * Utilizado para redimensionar uma imagem mantendo o aspecto dela
 */
const RESIZE_MAINTAIN_ASPECT = 0;

/**
 * Utilizado para redimensionar uma imagem diminuindo a caixa
 */
const RESIZE_BOX = 1;

/**
 * A extensão da imagem
 * @var string
 */
private $ext = self::DEFAULT_IMG_EXT;

/**
 * Recurso gerado pela GD
 * @var resource
 */
private $img;

/**
 * O nome do arquivo
 * @var string
 */
private $file;

/**
 * Qualidade que será utilizado para salvar uma imagem
 * @var integer
 */
public $quality = self::DEFAULT_IMG_QUALITY;

/**
 * Largura da imagem
 * @var integer
 */
public $width;

/**
 * Altura da imagem
 * @var integer
 */
public $height;

/**
 * Cria um novo objeto que será utilizado para manipular a imagem
 * @throws RuntimeException Se a GD não estiver instalada
 */
public function __construct() {
	if ( function_exists( 'gd_info' ) ){
		$this->width = 0;
		$this->height = 0;
	} else {
		throw new RuntimeException( 'GD não instalada' );
	}
}

/**
 * Destroi o recurso da imagem gerado pela GD
 */
public function __destruct() {
	if ( is_resource( $this->img ) ) imagedestroy( $this->img );
}

/**
 * Carrega a imagem
 * @param $string $file O nome do arquivo que será carregado
 * @return Image
 * @throws RuntimeException Se o arquivo não existir ou não tiver permissão de leitura no arquivo
 * @throws RuntimeException Se não for possível criar o recurso da imagem
 */
public function load( $file ) {
	$match = array();

	if ( is_resource( $this->img ) ){
		imagedestroy( $this->img );
	}

	if ( is_file( $file ) && is_readable( $file ) ) {
		$this->file = $file;

		if ( preg_match( '/[^\.]*\.(\w*)/' , $file , $match ) ){
			$this->ext = strtolower( $match[ 1 ] );
		}

		switch ( $this->ext ) {
			case 'png' :
				$this->img = imagecreatefrompng( $this->file );
				break;
			case 'gif' :
				$this->img = imagecreatefromgif( $this->file );
				break;
			case 'jpg' :
			default :
				$this->img = imagecreatefromjpeg( $this->file );
				break;
		}

		if ( is_resource( $this->img ) ){
			$this->width = imagesx( $this->img );
			$this->height = imagesy( $this->img );
		} else {
			throw new RuntimeException( 'Não foi possível criar o recurso da imagem' );
		}
	} else {
		throw new RuntimeException( 'O arquivo não existe ou não temos permissões de leitura' );
	}

	return $this;
}

/**
 * Redimensiona a imagem
 * @param integer $width A nova largura da imagem
 * @param integer $height A nova altura da imagem
 * @param integer $type Define se vamos manter o aspecto ou se vamos redimensionar a caixa
 * @return Image
 * @throws BadMethodCallException Se a imagem não tiver sido carregada
 */
public function resize( $width = null , $height = null , $type = self::RESIZE_MAINTAIN_ASPECT ) {
	if ( is_resource( $this->img ) ){
		$oldWidth = imagesx( $this->img );
		$oldHeight = imagesy( $this->img );
		$oldRatio = $oldWidth / $oldHeight;
		$newWidth = is_int( $this->width ) ? $this->width : $oldWidth;
		$newHeight = is_int( $this->height ) ? $this->height : $oldHeight;

		if ( is_int( $width ) ) $newWidth = $width;
		if ( is_int( $height ) ) $newHeight = $height;

		$tempimg = imagecreatetruecolor( $newWidth , $newHeight );
		imagecolorallocate( $tempimg , 255 , 255 , 255 );

		switch ( $type ) {
			case self::RESIZE_MAINTAIN_ASPECT :
				if ( ( $newWidth / $newHeight ) > $oldRatio ) {
					$newWidth = $newHeight * $oldRatio;
				} else {
					$newHeight = $newWidth / $oldRatio;
				}

				if ( imagecopyresampled( $tempimg , $this->img , 0 , 0 , 0 , 0 , $newWidth , $newHeight , $oldWidth , $oldHeight ) ){
					$this->img = $tempimg;
				}

				break;
			case self::RESIZE_BOX :
			default :
				if ( imagecopyresized( $tempimg , $this->img , 0 , 0 , 0 , 0 , $newWidth , $newHeight , $oldWidth , $oldHeight ) ){
					$this->img = $tempimg;
				}

				break;
		}

		$this->width = imagesx( $this->img );
		$this->height = imagesy( $this->img );
	} else {
		throw new BadMethodCallException( 'A imagem deve ser carregada antes' );
	}

	return $this;
}

/**
 * Salvamos a imagem para um arquivo
 * @param string $file O nome do arquivo que iremos salvar a imagem
 * @return Image
 * @throws BadMethodCallException Se a imagem não tiver sido carregada
 */
public function save( $file = null ) {
	if ( is_resource( $this->img ) ) {
		if ( is_null( $file ) ) $file = $this->file;

		switch ( $this->ext ) {
			case "png" :
				imagepng( $this->img , $file , $this->quality );
				break;
			case "gif" :
				imagegif( $this->img , $file , $this->quality );
				break;
			case "jpg" :
			default :
				imagejpeg( $this->img , $file , $this->quality );
				break;
		}
	} else {
		throw new BadMethodCallException( 'A imagem deve ser carregada antes' );
	}

	return $this;
}

/**
 * Enviamos a imagem para a saída padrão
 * @return Image
 * @throws BadMethodCallException Se a imagem não tiver sido carregada
 */
public function flush() {
	if ( is_resource( $this->img ) ){
		switch ( $this->ext ) {
			case "png" :
				imagepng( $this->img );
				break;
			case "gif" :
				imagegif( $this->img );
				break;
			case "jpg" :
			default :
				imagejpg( $this->img , null , $this->quality );
				break;
		}
	} else {
		throw new BadMethodCallException( 'A imagem deve ser carregada antes' );
	}

	return $this;
}
}

 

Para usar:

 

<?php
require 'Image.php';

$image = new Image();
$image->load( 'imagem.jpg' )->resize( 800 , 600 )->save();

Compartilhar este post


Link para o post
Compartilhar em outros sites

João , muito interessante esse código seu , mas aonde que ele irá salvar a imagem ?

 

Você tem duas opções:

 

1. Chamar o método save() sem nenhum parâmetro. Dessa forma o arquivo de origem será sobrescrito.

2. Passar um caminho para o método save(). Dessa forma um novo arquivo será criado, com as novas dimensões, preservando a imagem original.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Mas nesse caso daria só para eu definir a largura que calcularia a altura automaticamente?

 

pego a imagem como:

$files = $_FILES['imagem']['tmp_name'];

 

e para salvar:

copy($imagem,"../arquivos/$pasta/$imagem_salvar");

????

Compartilhar este post


Link para o post
Compartilhar em outros sites

Primeiro utilize a função move_uploaded_file() para mover a imagem do upload para um lugar conhecido.

 

Feito isso, faça o redimensionamento.

 

O método resize() trabalha com proporções, então ele fará o redimensionamento utilizando a largura e altura que você informar proporcionalmente, ajustando as novas dimensões segundo as proporções da imagem.

Compartilhar este post


Link para o post
Compartilhar em outros sites

João , estou tentando utilizar seu codigo , só que ele me da um erro .

 

Fatal error: Call to undefined function imagejpg() in ... on line 227

O que pode ser ?

 

Felipe.

 

Atualizando...

 

Resolvi o problema , é so uma falta de um 'e' imagejpg -> imagejpeg.

 

;)

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.