PHP Imagick addNoiseImage() 函数
Imagick::addNoiseImage() 方法是一个用于给给定图片添加噪声的 PHP 内置函数。产生的噪声量由噪声常量和通道种类决定。图像中亮度和对比度的随机变化被称为图像噪声。
语法:
bool Imagick::addNoiseImage ( noise_type,channel )
此函数接受如上所述的以下参数:
- $noise_type: 使用此选项选择噪声类型。以下是Imagick函数中的一些可用噪声常量:
- imagick::NOISE_UNIFORM(整数)
- imagick::NOISE_GAUSSIAN(整数)
- imagick::NOISE_MULTIPLICATIVEGAUSSIAN(整数)
- imagick::NOISE_IMPULSE(整数)
- imagick::NOISE_LAPLACIAN(整数)
- imagick::NOISE_POISSON(整数)
- imagick::NOISE_RANDOM(整数)
- 如果Imagick已编译为ImageMagick版本6.3.6或更高版本,则此常量可用。
- $channel: 此参数提供了通道常量。可以使用位运算符来组合两个或多个通道。以下是Imagick函数中的一些可用通道常量:
- imagick::CHANNEL_UNDEFINED(整数)
- imagick::CHANNEL_RED(整数)
- imagick::CHANNEL_GRAY(整数)
- imagick::CHANNEL_CYAN(整数)
- imagick::CHANNEL_GREEN(整数)
- imagick::CHANNEL_MAGENTA(整数)
- imagick::CHANNEL_BLUE(整数)
- imagick::CHANNEL_YELLOW(整数)
- imagick::CHANNEL_ALPHA(整数)
- imagick::CHANNEL_OPACITY(整数)
- imagick::CHANNEL_MATTE(整数)
- imagick::CHANNEL_BLACK(整数)
- imagick::CHANNEL_INDEX(整数)
- imagick::CHANNEL_ALL(整数)
- imagick::CHANNEL_DEFAULT(整数)
返回值
add noise Image函数的返回类型是布尔类型,这意味着该函数的返回类型要么为真,要么为假。此函数的返回值取决于添加噪声操作的成功与否。如果成功将噪声添加到指定图像,则此函数的返回类型将为True,表示成功将噪声添加到我们的图像。另一方面,如果添加噪声操作失败或由于指定了错误的参数而引发了问题,则返回类型将为失败,表示添加噪声到图像的操作失败。
示例1
<?php
/**
* sCAPTCHA - A simple CAPTCHA generator.
*
*/
define('ROOT_DIR', __DIR__);
define('FONT_DIR', __DIR__ . '/fonts/');
define('STORE_DIR', __DIR__ . '/store/');
class sCAPTCHA {
// configurables (see defaults below)
private configurables = array(
'session', // save generated key on session (boolean)
'session_name', // session name (string)
'hash', // hash generated key (boolean)
'length', // captcha character length
'table', // characters used in generating random captcha string
'readable', // use vowels and consonants for captcha readability (boolean)
'salt', // salt used for hashed key
'font', // font name
'height', // captcha image height
'width', // captcha image width
'wave', // wave effect, amplitude and length (array)
'swirl', // swirl effect (integer)
'noise', // add (effect) background noise (boolean)
'custom_font', // use custom font instead of the default one (boolean)
'custom_font_name', // custom font name
'font_size', // font size
'format', // file format (png, jpeg, or gif)
'store', // store generated image to a file (boolean)
'store_path' // where to store generated image
);
// Colors from http://www.imagemagick.org/script/color.php
privatecolor_table = array(
'#FF0000', // red
'#0000FF', // blue
'#008000', // green
'#000000' // black
);
private format_table = array(
'png', // PNG
'jpeg', // JPEG
'jpg', // JPEG
'gif' // GIF
);
// set default configurations
privatesession = false;
private session_name = 'sCAPTCHA';
privatehash = true;
private salt = null; // salt used for hashed key (default none)
privatelength = 5;
private table = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
privatereadable = true;
private noise = false;
privatecustom_font = false;
private custom_font_name = 'Moms_typewriter.ttf'; // default custom font
privatefont = 'Arial'; // default font
private font_size = 35; // default font size
// captcha image default size
privatewidth = 200;
private height = 57;
// text/image effects
privateswirl = 10;
private wave = array(
'amplitude' => 5,
'length' => 50
);
privatenoise_type = 3;
private noise_channel = 3;
// generated key store
privatekey = null;
// default image format
private format = 'png';
privatestore = false;
private store_path = STORE_DIR;
// instantiate
public function __construct() {
// set additional default variablesthis->wave_default = this->wave;this->format_default = this->format;this->store_path_default = STORE_DIR;
}
// override default configuration
public function config(config = null) {
if (isset(config) && is_array(config)) {
foreach (config as k =>v) {
if (in_array(k,this->configurables) && isset(v)) {this->k =v;
}
}
}
}
// generate random key based on the character table
public function key() {
if (this->readable) {this->key = this->easyRead();
} else {
for (i = 0; i <=this->length; i++) {this->key .= this->table{rand(0, (strlen(this->table) - 1))};
}
}
// check if to use session to save generated key
if (this->session) {
// check if session is enabled, if not start session
if(session_id() == "") {
session_start();
// check if generated key need to be hashed
if (this->hash) {
_SESSION[this->session_name] = sha1(this->key .this->salt);
} else {
_SESSION[this->session_name] = this->key;
}
}
}
returnthis->key;
}
// generate readable challenge string
// based from http://www.phpsnippets.info/generate-a-password-in-php
public function easyRead() {
vowels = 'aeuyAEUY';consonants = 'bdghjmnpqrstvzBDGHJLMNPQRSTVWXZ';
string = '';alt = time() % 2;
for (i = 0;i < this->length;i++) {
if (alt == 1) {string .= consonants[(rand() % strlen(consonants))];
alt = 0;
} else {string .= vowels[(rand() % strlen(vowels))];
alt = 1;
}
}
returnstring;
}
// generate captcha image
public function captcha() {
// get generated characters
if (!is_null(this->key) && isset(this->key)) {
text =this->key;
} else {
text =this->key(); // generate key
}
// create Imagick objects
image = new Imagick();draw = new ImagickDraw();
font_color = new ImagickPixel(this->color_table{rand(0, (count(this->color_table) - 1))});background = new ImagickPixel('#ffffff'); // white
// font properties
if (!this->custom_font) {draw->setFont(this->font);
} else {
// check if custom font file exists
if (file_exists(FONT_DIR .this->custom_font_name)) {
draw->setFont(FONT_DIR .this->custom_font_name);
} else {
draw->setFont(this->font); // fallback to the default font
}
}
draw->setFontSize(this->font_size);
draw->setFillColor(font_color);
// get font metrics for centering text string
fm =image->queryFontMetrics(draw,text, false);
coordinate_x = (this->width / 2) - (fm["textWidth"] / 2);coordinate_y = this->height - (fm["textHeight"] / 2);
// create text
draw->annotation(coordinate_x, coordinate_y,text);
// create image
image->newImage(this->width, this->height,background);
// check if file/image format is valid
format_setting = strtolower(this->format);
if (in_array(format_setting,this->format_table)) {
if (format_setting == 'jpeg') {format_setting = 'jpg';
}
image_format =format_setting;
} else {
image_format =this->format_default; // fallback to the default file/image format
}
image->setImageFormat(image_format);
image->drawImage(draw);
// add image effects
// wave
if (is_array(this->wave)) {image->waveImage(this->wave['amplitude'],this->wave['length']);
} else {
image->waveImage(this->wave_default['amplitude'], this->wave_default['length']);
}
// swirlimage->swirlImage(this->swirl);
// background noise
if (this->noise) {
image->addNoiseImage(this->noise_type, this->noise_channel);
}
// check if generated image will be saved as a file
if (this->store) {
filename = md5(time()) . '.' .image_format; // construct file's name
// check if directory exists
if (file_exists(this->store_path)) {store_file_path = rtrim(this->store_path, '/') . '/' .filename;
} elseif (file_exists(this->store_path_default)) { // try the default store pathstore_file_path = rtrim(this->store_path_default, '/') . '/' .filename;
} else {
// try creating the default store path
if (!mkdir(rtrim(this->store_path_default, '/'))) {
return false;
}store_file_path = rtrim(this->store_path_default, '/') . '/' .filename;
}
// store/save image file
file_put_contents(store_file_path,image);
return filename; // return only the file's name
} else {
// return generated image
returnimage;
}
}
}
输出:
上面写的示例展示了PHP提供的添加噪音图像函数的一个使用场景。在这个示例中,使用了add_noise_image函数来创建验证码图像。这个验证码图像是通过使用这个函数的帮助来添加故意的噪音而制作的。如今,验证码图像在互联网上广泛用于验证人类和机器人在互联网上访问各种网站时的区别。
示例2
/**
* Creates image with text
* @param int sizeX
* @param intsizeY
* @param string text
* @param stringgenerator
* @return \Imagick
*/
public function mkCapcha(sizeX,sizeY, text,generator = self::METHOD_DEFAULT)
{
// init image
image = new \Imagick();image->newImage(sizeX,sizeY, new \ImagickPixel('white'));
image->setImageFormat('png');
switch (generator) {
case self::METHOD_GRAYNOISE:
draw = new \ImagickDraw();draw->setFontSize(35);
draw->setFontWeight(900);draw->setGravity(\imagick::GRAVITY_CENTER);
image->addNoiseImage(\imagick::NOISE_LAPLACIAN);image->annotateImage(draw, 0, 0, 0,text);
image->charcoalImage(2, 1.5);image->addNoiseImage(\imagick::NOISE_LAPLACIAN);
image->gaussianBlurImage(1, 1);
break;
case self::METHOD_GRAYBLUR:draw = new \ImagickDraw();
order = [];
for (i = 0; itext); i++) {order[i] =i;
}
shuffle(order);
for (j = 0; j<2;j++) {
shuffle(order);image->gaussianBlurImage(15, 3);
for (n = 0;n < strlen(text);n++) {
i =order[n];draw->setFont(__DIR__ . '/Capcha/DejaVuSans.ttf');
draw->setFontSize(j ? rand(sizeY * 3 / 5,sizeY * 5 / 6) : rand(sizeY * 4 / 6,sizeY * 5 / 6));
draw->setFontWeight(rand(100, 900));draw->setGravity(\imagick::GRAVITY_CENTER);
image->annotateImage(draw, (i - strlen(text) / 2) * sizeX / (strlen(text) + 2.3), 0, rand(-25, 25), text[i]);
image->gaussianBlurImage(1, 1);
}
}
break;
}
returnimage;
}
输出:
这是另一个示例,展示了在PHP中使用添加噪声图像函数的用例场景。在这个示例中,我们使用这个函数向任何图像添加了故意的噪声。在这个函数中,我们需要使用不同的方法,如灰蓝方法和灰色噪声方法。通过这些参数,我们可以控制向图像中引入的噪声的类型和数量。
在本文中,我们已经通过了PHP提供的添加噪声图像函数的用例场景,并了解了传递给此函数的使用和不同参数的方法,以及我们如何使用可用于操作图像中引入的噪声的类型,数量和精度的不同参数集合。