1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > PHP将图片转换成base64编码 hash函数

PHP将图片转换成base64编码 hash函数

时间:2021-09-06 19:08:23

相关推荐

PHP将图片转换成base64编码 hash函数

PHP将图片转换成base64编码,hash函数

一、图片转换成base64编码

1、在线转换

2、PHP转换代码:

public function testAction(){

$fileInfo = $_FILES['address']; //input type='file' name='address'

/** $fileInfo的值 */

/* array (

'name' => '2.jpg',

'type' => 'image/jpeg',

'tmp_name' => 'D:\\xampp\\tmp\\php591E.tmp',

'error' => 0,

'size' => 115023,

) */

$image_path = $fileInfo['tmp_name'];

$base64_image = $this->getImageBase64($image_path);

@unlink($image_path); //删除服务器上临时文件,屏蔽警告

var_export($base64_image); 结果有点长截取部分: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAY......uw8G3CC8kBH3aK4JRlcr2R//Z

die;

}

/**

* @todo 根据文件路径获取文件的base编码

* @param unknown $image_path 文件路径

* @return string 返回编码内容

*/

function getImageBase64($image_path){

$image_info = getimagesize($image_path);

/** $image_info的值 */

/* array (

0 => 1080,

1 => 720,

2 => 2,

3 => 'width="1080" height="720"',

'bits' => 8,

'channels' => 3,

'mime' => 'image/jpeg',

) */

/*

//list() 仅能用于数字索引的数组,并假定数字索引从 0 开始。

list($width,$height,$type,$width_height_str) = getimagesize($file_path); // √ 等价于 $image_info[0] $image_info[1] $image_info[2] $image_info[3]

list($width,$height,$type,$width_height_str,$b,$c,$m) = getimagesize($file_path); // × Notice: Undefined offset: 4 in ../Test.php on line 57

// × Notice: Undefined offset: 5 in ../Test.php on line 57

// × Notice: Undefined offset: 6 in ../Test.php on line 57

*/

$image_data = fread(fopen($image_path, 'r'), filesize($image_path));

$base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));

return $base64_image;

}

3、getimagesize)()返回结果说明:

索引 0 给出的是图像宽度的像素值

索引 1 给出的是图像高度的像素值

索引 2 给出的是图像的类型,返回的是数字,其中1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,6 = BMP,7 = TIFF(intel byte order),8 = TIFF(motorola byte order),9 = JPC,10 = JP2,11 = JPX,12 = JB2,13 = SWC,14 = IFF,15 = WBMP,16 = XBM

索引 3 给出的是一个宽度和高度的字符串,可以直接用于 HTML 的 <image> 标签

索引 bits 给出的是图像的每种颜色的位数,二进制格式

索引 channels 给出的是图像的通道值,RGB 图像默认是 3

索引 mime 给出的是图像的 MIME 信息,此信息可以用来在 HTTP Content-type 头信息中发送正确的信息,如: header("Content-type: image/jpeg");

二、hash()函数

1、hash — 生成哈希值 (消息摘要)

语法:string hash ( string $algo , string $data [, bool $raw_output = FALSE ] )

参数说明:

参数 说明

algo 要使用的哈希算法,例如:"md5","sha256","haval160,4" 等。

函数 hash_algos(); //获取已注册的哈希算法列表[一维数组]

data 要进行哈希运算的消息。

raw_output 设置为 TRUE 输出原始二进制数据, 设置为 FALSE 输出小写 16 进制字符串。

使用案例:

//用哈希的 sha256算法

function testAction(){

$time = time();

$str = "appkey=14000****23&random=7226249334&time={$time}";

$sig = hash('sha256', $str);

var_export($sig); //6798d768489074d9b7d469942336fb11edbe5b3a31fa791d10e0bef50f45670f

die;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。