ГлавнаяФорумыЧАТСкрипты/PHP/MySQL/CSS/HTML

Полезные PHP коды

InkMission[78] (Off)
[06.02.11, 22:28]
Анимационный текст (GIF)
<?php

$animation = new Imagick();

$animation->setFormat('gif');



$color = new ImagickPixel('white');

$color->setColor('white');

$string = 'PHPcodes.RU';

$draw = new ImagickDraw();

//$draw->setFont('Arial');

for ($i = 0; $i <= strlen($string); $i++)

{

$part = substr($string, 0, $i);



$animation->newImage(100, 40, $color);



$animation->annotateImage($draw, 10, 20, 0, $part);

$animation->setImageDelay(30);

}



//$draw->setFont('Arial-Bold');

$draw->setTextDecoration(imagick::DECORATION_UNDERLINE);

$animation->newImage(100, 40, $color);



$animation->annotateImage($draw, 10, 20, 0, $string);

$animation->setImageDelay(70);

header('Content-Type: image/gif');

echo $animation->getImagesBlob();

?>
InkMission[78] (Off)
[06.02.11, 22:28]
Детальная информация об изображении
<?php

$im = new Imagick('image.jpg');

$info = $im->identifyImage();

echo'<strong>Базовые свойства картинки:</strong><br/>';

echo'Разрешение: '.$info['geometry'] ['width'].'x'.$info['geometry']['height'].'<br/>';

echo'Формат: '.$info['format'].'<br/>';

echo'Тип: '.$info['type'].'<br/>';

echo'Сжатие: '.$info['compression'].'<br/>';

echo'Размер: '.$info['fileSize'].'<br />';

echo'<br/><br/>';

echo'<strong>Все свойства картинки:</strong><br/>';



foreach ($im->getImageProperties() as $key => $val)

{

echo $key.' => '.$val.'<br/>';

}



echo'<strong>Все профили картинки:</strong><br/>';

foreach ($im->getImageProfiles() as $key => $val)

{

echo'Название: '.$key.' (Размер: '.strlen($val).')<br/>';

}

?>
InkMission[78] (Off)
[06.02.11, 22:29]
Класс смайлов
<?php

class Smiles

{

private $pack = 'default'; //смайлпак

private $dir = '/smiles/';

private $smiles_list = 'smiles.list'; //список смайлов

private $data = array();





public function __construct($config = array())

{

foreach($config as $key=>$val)

$this->$key = $val;

$file = file($_SERVER['DOCUMENT_ROOT'].$this->dir.$this->pack.'/'.$this->smiles_list);

$rows = sizeof($file);

list($delimiter, $ext) = explode('###', $file[0]);

for($i = 1; $i < $rows; $i++)

{

$arr = explode($delimiter, $file[$i]);

foreach($arr as $val)

{

$val = trim($val);

$this->data[$val] = '<img src="'.$this->dir.$this->pack.'/'.$i.'.'.$ext.'" alt="'.$val.'"/>';

}

}

}



public function replace($text)

{

return strtr($text, $this->data);

}

}

?>
InkMission[78] (Off)
[06.02.11, 22:29]
Скругление углов
<?php

/**

* Углоскруглятель

* * Sergey Fedotov <[email protected]>

* Version: 1.1

*/

$filename ='image.jpg';

$radius = 15;

/**

* Чем выше rate, тем лучше качество сглаживания и больше время обработки и

* потребление памяти.

* * Оптимальный rate подбирается в зависимости от радиуса.

*/

$rate = 3;

$img = imagecreatefromstring(file_get_contents($filename));

imagealphablending($img, false);

imagesavealpha($img,true);

$width = imagesx($img);

$height = imagesy($img);

$rs_radius = $radius *$rate;

$rs_size = $rs_radius *2;

$corner =imagecreatetruecolor($rs_size, $rs_size);

imagealphablending($corner, false);

$trans = imagecolorallocatealpha($corner, 255, 255, 255, 127);

imagefill($corner, 0, 0,$trans);

$positions = array(

array(0, 0, 0, 0),

array($rs_radius, 0,$width-$radius, 0),

array($rs_radius,$rs_radius, $width-$radius, $height-$radius),

array(0, $rs_radius, 0,$height-$radius),

);

foreach ($positions as $pos) {

imagecopyresampled($corner, $img, $pos[0],$pos[1], $pos[2], $pos[3], $rs_radius,$rs_radius, $radius, $radius);

}

$lx = $ly = 0;

$i =-$rs_radius;

$y2 =-$i;

$r_2 = $rs_radius *$rs_radius;

for (; $i <= $y2; $i++) {

$y = $i;

$x = sqrt($r_2-$y * $y);

$y += $rs_radius;

$x += $rs_radius;

imageline($corner, $x,$y, $rs_size, $y, $trans);

imageline($corner, 0,$y, $rs_size-$x, $y,$trans);

$lx = $x;

$ly = $y;

}

foreach ($positions as $i => $pos) {

imagecopyresampled($img, $corner, $pos[2],$pos[3], $pos[0], $pos[1], $radius, $radius,$rs_radius, $rs_radius);

}

header('Content-Type: image/png');

imagepng($img);

imagedestroy($img);

?>
InkMission[78] (Off)
[06.02.11, 22:30]
Конвертор форматов изображений
<?php

$to = 'png';

$save_as = 'filename.'.$to;

$file = 'picture.gif';

$type = substr($file, strrpos($file,'.')+1);

if($type == 'jpg')

$type = 'jpeg';

switch($type)

{

case('jpeg'):

$image = imagecreatefromjpeg($file);

break;

case('gif'):

$image = imagecreatefromgif($file);

break;

case('png'):

$image = imagecreatefrompng($file);

break;

}



switch($to)

{

case('jpeg'):

imagejpeg($image, $save_as);

break;

case('gif'):

imagegif($image, $save_as);

break;

case('png'):

imagepng($image, $save_as);

break;

}

?>
InkMission[78] (Off)
[06.02.11, 22:30]
Мини-диаграмма в виде полоски
<?php

//Определяем сколько надо закрасить

$p = (isset($_GET['p']) && $_GET['p']>=0 && $_GET['p']<=100) ? (int)$_GET['p'] : 50;

//Создаем картинку

$image = imagecreate(123,  ;

//Цвет фона

$bg = imagecolorallocate ($image, 0, 0, 0);

//Цвет активной части и надписи к-ва %

$act = imagecolorallocate($image, 210, 210, 210);

//Цвет пассивной части

$emp = imagecolorallocate($image, 250, 250, 250);

imagefill($image, 0, 0, $bg);

imagefilledrectangle($image, 1, 1, 100, 6, $emp);

if($p > 0)

imagefilledrectangle($image, 1, 1, $p, 6, $act);

//Пишем к-во %

imagestring($image, 1, 102, 0, $p.'%', $act);

header('Content-type: image/png');

imagepng($image);

imagedestroy($image);

?>
InkMission[78] (Off)
[06.02.11, 22:31]
Генератор градиентов
<?php

//определяем тип: вертикальный или горизонтальный

$type = (isset($_GET['type']) && $_GET['type'] == 'g') ? 'g' : 'v';

//определяем высоту

$height = (isset($_GET['h'])) ? abs((int)$_GET['h']) : 100;

//определяем ширину

$width = (isset($_GET['w'])) ? abs((int)$_GET['w']) : 60;



//определяем цвета

$start = (isset($_GET['s']) && preg_match('#[0-9A-F]{6}#',$_GET['s'])) ? $_GET['s'] : '000000';

$end = (isset($_GET['e']) && preg_match('#[0-9A-F]{6}#',$_GET['e'])) ? $_GET['e'] : 'FFFFFF';

//определяем RGB этих цветов

$start_r= hexdec(substr($start, 0, 2));

$start_g = hexdec(substr($start, 2, 2));

$start_b = hexdec(substr($start, 4, 2));

$end_r = hexdec(substr($end, 0, 2));

$end_g = hexdec(substr($end, 2, 2));

$end_b = hexdec(substr($end, 4, 2));

//создаём картинку

$image = imagecreate($width, $height);

//определяем тип и рисуем градиент

if($type == 'g'){

for($x=0; $x<$width; $x++){

$new_r = $start_r - intval(($start_r - $end_r) / $width * $x);

$new_g = $start_g - intval(($start_g - $end_g) / $width * $x);

$new_b = $start_b - intval(($start_b - $end_b) / $width * $x);

$row_color = imagecolorresolve($image, $new_r, $new_g, $new_b);

imageline($image, $x, 0, $x, $height, $row_color);

}

}else{

for($y=0; $y<$height; $y++){

$new_r = $start_r - intval(($start_r - $end_r) / $height * $y);

$new_g = $start_g - intval(($start_g - $end_g) / $height * $y);

$new_b = $start_b - intval(($start_b - $end_b) / $height * $y);

$row_color = imagecolorresolve($image, $new_r, $new_g, $new_b);

imageline($image, 0, $y, $width, $y, $row_color);

}

}

header('Content-type: image/png');

imagepng($image);

imagedestroy($image);

//вот и всё

?>
InkMission[78] (Off)
[06.02.11, 22:31]
Увеличение картинки со сглаживанием
<?php
$from = imageCreateFromJpeg("sample2.jpg");
$to = imageCreateTrueColor(2000, 2000);
imageCopyResampled(
$to, $from, 0, 0, 0, 0, imageSX($to), imageSY($to),
imageSX($from), imageSY($from)
);
header("Content-type: image/jpeg");
imageJpeg($to);
?>
InkMission[78] (Off)
[06.02.11, 22:32]
Функция смены тональности песен
<?php
function alterate($chords_string, $half_tones_alt)
{
$data_half_tones = array(
0 => 'C',
2 => 'D',
4 => 'E',
5 => 'F',
7 => 'G',
9 => 'A',
10 => 'B',
11 => 'H',
);

$wrong_alts = array(
'A#' => 'B',
'B#' => 'H',
'H#' => 'C',
'E#' => 'F',
);

$data_chords = array_flip($data_half_tones);

$strlen = strlen($chords_string);
$return = '';

for($i = 0; $i < $strlen; $i++)
{
if(in_array($chords_string[$i], $data_half_tones))
{
$new_tone = $data_chords[$chords_string[$i]] + $half_tones_alt;
$new_tone = ($new_tone > 11 ? $new_tone % 12 : $new_tone);
$return .= (array_key_exists($new_tone, $data_half_tones)
? $data_half_tones[$new_tone]
: (array_key_exists($data_half_tones[$new_tone - 1].'#', $wrong_alts)
? $wrong_alts[$data_half_tones[$new_tone - 1].'#']
: $data_half_tones[$new_tone - 1].'#'
)

);

}
else
{
$return .= $chords_string[$i];
}

}



return $return;
}

echo alterate('Em H7 Em H7', +2);

//F#m C#7 F#m C#7
?>
InkMission[78] (Off)
[06.02.11, 22:32]
Пишим теги id2v1 и id2v2 в MP3 файл
<?php
define(_Title,"TIT2");
define(_Artist,"TPE1");
define(_Group,"TPE2");
define(_Album,"TALB");
define(_Genre,"TCON");
define(_TrackNo,"TRCK");
define(_Year,"TYER");
$frames = array(_Album=>"Album 2",
_TrackNo=>"1",
_Title=>"Name Song",
_Artist=>"Name Artist",
_Group=>"Name Group",
_Year=>"2010",
_Genre=>"Other");

#..........................................
# WRITE ID3 TAGS (Write MP3 [v1, v2]
#..........................................
function writeTags($mp3) {
$fl = file_get_contents($mp3);
$Header = substr($fl,0,10);
$tagLen = calcDecTagLen(substr($Header,6,4),$tagLen);
$music = substr($fl,$tagLen+10,-128);
# Can use input Header for output but you may
# wish to change the output filename for testing
$tagLen = 1024; # or whatever you like >your actual
$Header = substr($Header,0,6).setHexTagLen($tagLen);
file_put_contents($mp3,mkV2Tag($Header,$tagLen).$music.mkV1Tag());
}
# Create the V2 tag
function mkV2Tag($Hdr,$tagLen) {
Global $frames;
$null = chr(0);
$nl3 = $null.$null.$null; # 0 bytes for flags and encoding
$out = "";
foreach($frames as $ky=>$val) {
$n=strlen($val)+1;
$out.= $ky.mkFrmLen($n).$nl3.$val;
}
return $Hdr.str_pad($out,$tagLen,$null);
}
# Calculate Tag Length from bytes 6-10 of existing header
function calcDecTagLen($word) {
$m = 1;
$int = 0;
for ($i=strlen($word)-1;$i>-1;$i--) {
$int +=$m*ord($word[$i]);
$m=$m*128;
}
return $int;
}
# Make the 4 byte frame length value for the V2tag
function mkFrmLen($int) {
$hx = "";
while ($int>0) {
$n = $int % 256;
$hx = chr($n).$hx;
$int=floor($int/256);
}
return str_pad($hx,4,chr(0),STR_PAD_LEFT);
}
# Create the 128 byte V1 tag
function mkV1Tag() {
Global $frames;
$tagOut = "TAG".
adj($frames[_Title]).
adj($frames[_Artist]).
adj($frames[_Album]).
str_pad($frames[_Year],4).
str_pad(" ",29," ").
chr($frames[_TrackNo]).
chr($n);
return $tagOut;
}
# Pad the header to 30 characters
function adj($str) {
return substr(str_pad($str,30,chr(0)),0,30);
}
function setHexTagLen($int) {
$n = pow(128,3);
$intVar = $int;
$m = "";
for ($i=0;$i<4;$i++) {
$m .= chr(floor($intVar/$n));
$intVar = $intVar % $n;
$n=$n/128;
}
return $m;
}
////// EXAMPLE
writeTags('song_files.mp3');
?>
Последние ответы