<?php
namespace app\index\controller;

use think\Controller;


/**
 * 图片直方图对比测试
 */
class Histogram extends controller
{
	
	function index()
	{
		
		$random1 = session('img_key_3');
		$random2 = session('img_key_4');
		if(!$random1){
			$random1 = get_rand_string();
			session('img_key_3',$random1);
		}
		if(!$random2){
			$random2 = get_rand_string();
			session('img_key_4',$random2);
		}
		$this->assign('random1',$random1);
		$this->assign('random2',$random2);
		$basePath = ROOT_PATH.'public'.DS.'img'.DS.'calendar'.DS;
		$fileConfig = iniConfig($basePath.'config.ini',true);
		$file1 = $fileConfig['file3']?$fileConfig['file3']:'3.png';
		$file2 = $fileConfig['file4']?$fileConfig['file4']:'4.png';
		$this->assign('file1',$file1);
		$this->assign('file2',$file2);
		if(file_exists($basePath . $file1)){
			$exif1 = \exif_read_data($basePath . $file1);
			$this->assign('exif1',$exif1);
		}
		if(file_exists($basePath . $file2)){
			$exif2 = \exif_read_data($basePath . $file2);
			$this->assign('exif2',$exif2);
		}



		return $this->fetch();
	}
	function tu(){
		$id = input('id');
		$type = input('type');
		if($type){
			$type = explode(',', $type);
		}else{
			$type = ['r','g','b'];
		}
		$file = ROOT_PATH.'public'.DS.'img'.DS.'calendar'.DS.$id.'.png';
		$size = array(
			'width' => 256,
			'height' => 100,
		);
		$image = new \Imagick($file);
		$histogram = array_fill_keys(range(0, 255), 0);
		foreach ($image->getImageHistogram() as $pixel) {
			$rgb = $pixel->getColor();
			if(in_array('r', $type)){
				$histogram[$rgb['r']] += $pixel->getColorCount();
			}
			if(in_array('g', $type)){
				$histogram[$rgb['g']] += $pixel->getColorCount();
			}
			if(in_array('b', $type)){
				$histogram[$rgb['b']] += $pixel->getColorCount();
			}
		}
		$max = max($histogram);
		$threshold = ($image->getImageWidth() * $image->getImageHeight()) / 256 * 12;
		if ($max > $threshold) {
		$max = $threshold;
		}
		\Imagick::setResourceLimit(\Imagick::RESOURCETYPE_MEMORY,102400000);
		\Imagick::setResourceLimit(\Imagick::RESOURCETYPE_MAP,102400000);
		$image = new \Imagick();
		$draw = new \ImagickDraw();
		$image->newImage($size['width'], $size['height'], 'white');
		foreach ($histogram as $x => $count) {
			if ($count == 0) {
				continue;
			}
			$draw->setStrokeColor('black');
			$height = min($count, $max) / $max * $size['height'];
			$draw->line($x, $size['height'], $x, $size['height'] - $height);
			$image->drawImage($draw);
			$draw->clear();
		}
		$image->setImageFormat('png');

		// $image->writeImage('histogram.png');
		// header("Content-Type: image/png");
		echo $image->getimageblob();
		// echo \Imagick::getResourceLimit(\Imagick::RESOURCETYPE_MEMORY);
		$a = $image->clear();
		$b = $image->destroy();
		$c = $draw->destroy();
		unset($image,$draw,$histogram);
		// var_dump($a);
		// var_dump($b);
		// var_dump($c);
		// echo round(memory_get_usage()/1024/1024, 2).'MB';
	}
	function diff(){
		$ori = input('ori');
		$dst = input('dst');
		$type = input('type');
		$img1 = 'http://61crm.c.suxuantech.cn:7778/histogram/'.$ori.($type?'?type='.$type:'');
		$img2 = 'http://61crm.c.suxuantech.cn:7778/histogram/'.$dst.($type?'?type='.$type:'');

		/*
		$context = stream_context_create(array(
			'http' => array(
				//'method'=>'get',
				'timeout' => 10, //超时时间，单位为秒
				'header'=>'Connection: keep-alive\r\n'
				)
			)
		);  
		$file = file_get_contents($img1,false,$context);
		// $file = file_get_contents($img1);
		var_dump($file);die;
		$file1 = file_get_contents($img1, 0, $context);
		$file2 = file_get_contents($img2, 0, $context);
		//*/
		// var_dump($img1);die;
		$images1 = imagecreatefrompng($img1);
		$images2 = imagecreatefrompng($img2);
		$x1 = imagesx($images1);
        $y1 = imagesy($images1);

        $x2 = imagesx($images2);
        $y2 = imagesy($images2);

        $w1 = $x1 < $x2 ? $x1 : $x2;
        $h1 = $y1 < $y2 ? $y1 : $y2;

        //$newimg = imagecreatetruecolor($w1, $h1);

        for ($i=0; $i < $w1; $i++) { // 遍历图片的像素点
            for ($j=0; $j < $h1; $j++) {
                $rgb = imagecolorat($images1, $i, $j); // 取第一个图的当前位置值
                $rgb2 = imagecolorat($images2, $i, $j); // 取第二个图的当前位置值
                if($rgb == $rgb2 && $rgb2 === 0){
                	imagesetpixel($images1, $i, $j, 255);
                }
                if($rgb != $rgb2 && $rgb === 255){
                	imagesetpixel($images1, $i, $j, $rgb2);
                }
                /*
                if (!$rgb) { // 是黑色【0，0，0】的，就取值
                    $color = imagecolorat($imgCrop, $i, $j); // 在用户的图片上对应的地方取色值
                    imagesetpixel($img, $i, $j, $color); // 在透明底图上画出要裁剪出来的部分
                }*/
            }
        }
        imagepng($images1);
	}

	function diffdata(){
		$ori = input('ori');
		$dst = input('dst');
		$type = input('type');
		$img1 = 'http://61crm.c.suxuantech.cn:7778/histogram/'.$ori.($type?'?type='.$type:'');
		$img2 = 'http://61crm.c.suxuantech.cn:7778/histogram/'.$dst.($type?'?type='.$type:'');

		$images1 = imagecreatefrompng($img1);
		$images2 = imagecreatefrompng($img2);
		$x1 = imagesx($images1);
        $y1 = imagesy($images1);

        $x2 = imagesx($images2);
        $y2 = imagesy($images2);

        $w1 = $x1 < $x2 ? $x1 : $x2;
        $h1 = $y1 < $y2 ? $y1 : $y2;

        $total = 0;
        $totalori = 0;
        for ($i=0; $i < $w1; $i++) { // 遍历图片的像素点
            for ($j=0; $j < $h1; $j++) {
                $rgb = imagecolorat($images1, $i, $j); // 取第一个图的当前位置值
                if($rgb != 255){
                	//非白色的像素数
                	$totalori++;
                }
                $rgb2 = imagecolorat($images2, $i, $j); // 取第二个图的当前位置值
                if($rgb == $rgb2 && $rgb2 === 0){
                	// imagesetpixel($images1, $i, $j, 255);
                	$rgb = $rgb2 = 255;
                }
                if($rgb != $rgb2 && $rgb === 255){
                	// imagesetpixel($images1, $i, $j, $rgb2);
                	$rgb = $rgb2;
                }
                if($rgb != 255){
                	//非白色的像素数
                	$total++;
                }
                /*
                if (!$rgb) { // 是黑色【0，0，0】的，就取值
                    $color = imagecolorat($imgCrop, $i, $j); // 在用户的图片上对应的地方取色值
                    imagesetpixel($img, $i, $j, $color); // 在透明底图上画出要裁剪出来的部分
                }*/
            }
        }
        imagedestroy($images1);
        imagedestroy($images2);
        return json(['code'=>200,'data'=>['total'=>$total,'totalori'=>$totalori]]);
	}	
	function up(){
		set_time_limit(0);
		$file  = request()->file('file');
		$imgid  = input('img_id');
		$sessionKey = 'img_key_'.$imgid;
		session($sessionKey,null);
        //ini_set('memory_limit','1024M');
        $basePath = ROOT_PATH.'public'.DS.'img'.DS.'calendar'.DS;
        //上传验证后缀名,以及上传之后移动的地址
        $info = $file->validate(['ext' => 'jpg,gif,png,jpeg'])->move($basePath,$imgid);
        if ($info) {
            $fileName = $info->getSaveName();  //获取文件名
            $fileConfig = iniConfig($basePath.'config.ini',true);
            $fileConfig['file'.$imgid] = basename($fileName);
            iniConfig($basePath.'config.ini',$fileConfig);
            return json(array('code'=>200,'msg'=>'文件上传成功','data'=>$fileName));
        }else{
        	return json(array('code'=>100,'msg'=>'文件上传失败','error'=>$file->getError()));
        }
	}
	function getscore(){
		//光圈
		$fnumber = [
			1,1.4,2,2.8,3.2,3.5,4,4.5,5,5.6,6.3,7.1,8,9,10,11,13,14,16,18,20,22
		];
		//快门
		$kuaimen = [
			4,5,6,8,10,13,15,20,25,30,40,50,60,80,100,125,160,200,250,320,400,500,640,800,1000,1250,1600,2000
		];
		$iso = [
			100,125,160,200,250,320,400,500,640,800,1000,1250,1600,2000,2500,3200,4000,5000,6400
		];
		$data = input('');
		$zfavg = round(((int)$data['zfavg'] - 10000)/1000);
		$scoreZF = 100 - $zfavg;
		$scoreZF = $scoreZF >0 ? $scoreZF * 0.7 :0;
		$in_fnumber1 = (float)substr(input('fnumber1'), 0,strpos(input('fnumber1'), '/'));
		$in_fnumber2 = (float)substr(input('fnumber2'), 0,strpos(input('fnumber2'), '/'));

		$kfn1 = array_search($in_fnumber1, $fnumber);
		$kfn2 = array_search($in_fnumber2, $fnumber);
		if($kfn1 !== false && $kfn2 !== false){
			$reskfn = abs(abs($kfn1) - abs($kfn2));
			$scorekfn = 7.5 - $reskfn * 1.875;
			$scorekfn = $scorekfn > 0 ? $scorekfn : 0;
		}else{
			$scorekfn = 0;
		}


		$tmp1 = explode('/', input('exptime1'));
		$tmp2 = explode('/', input('exptime2'));

		$in_kuaimen1 = (float)$tmp1[1];
		$in_kuaimen2 = (float)$tmp2[1];
		
		$km1 = array_search($in_kuaimen1, $kuaimen);
		$km2 = array_search($in_kuaimen2, $kuaimen);
		if($km1 !== false && $km2 !== false){
			$reskm = abs(abs($km1) - abs($km2));
			$scorekm = 7.5 - $reskm * 1.875;
			$scorekm = $scorekm > 0 ? $scorekm : 0;
		}else{
			$scorekm = 0;
		}


		$tmp1 = explode('/', input('flength1'));
		$tmp2 = explode('/', input('flength2'));
		$in_flength1 = (float)($tmp1[0]/$tmp1[1]);
		$in_flength2 = (float)($tmp2[0]/$tmp2[1]);

		if($in_flength1 && $in_flength2){
			$reslf = abs($in_flength1 - $in_flength2);
			$scorelf = 7.5 - $reslf * 1.875;
			$scorelf = $scorelf > 0 ? $scorelf : 0;
		}else{
			$scorelf = 0;
		}

		$in_iso1 = (int)input('iso1');
		$in_iso2 = (int)input('iso2');

		$kiso1 = array_search($in_iso1, $iso);
		$kiso2 = array_search($in_iso2, $iso);
		if($kiso1 !== false && $kiso2 !== false){
			$resiso = abs(abs($kiso1) - abs($kiso2));
			$scoreiso = 7.5 - $resiso * 1.875;
			$scoreiso = $scoreiso > 0 ? $scoreiso : 0;
		}else{
			$scoreiso = 0;
		}

		return [
			'code'=>200,
			'data'=>[
				'scoreZF'=>$scoreZF,
				'scorekfn'=>$scorekfn,
				'scorekm'=>$scorekm,
				'scorelf'=>$scorelf,
				'scoreiso'=>$scoreiso,
				'all'=>$scoreZF + $scorekfn + $scorekm + $scorelf + $scoreiso,
			]
		];



	}
	function demo(){
		return $this->fetch();
	}
}