Mask over image - php-gd

I want to replace the transparent pixels of a image with a mask, I'm using this function but I keep getting errors.
When I try:
<?php
function image_mask($src, $mask)
{
imagesavealpha($src, true);
imagealphablending($src, false);
// scan image pixels
// imagesx = get image width
for ($x = 0; $x < imagesx($src); $x++) {
// imagesy = get image height
for ($y = 0; $y < imagesy($src); $y++) {
$mask_pix = imagecolorat($mask,$x,$y);
//return r,g,b,alpha
$mask_pix_color = imagecolorsforindex($mask, $mask_pix);
if ($mask_pix_color['alpha'] < 127) {
$src_pix = imagecolorat($src,$x,$y);
$src_pix_array = imagecolorsforindex($src, $src_pix);
imagesetpixel($src, $x, $y, imagecolorallocatealpha($src, $src_pix_array['red'], $src_pix_array['green'], $src_pix_array['blue'], 127 - $mask_pix_color['alpha']));
}
}
}
}
image_mask('source.png', 'mask.png');
?>
I get the following errors:
Warning: imagesavealpha() expects parameter 1 to be resource, string given in ... on line 7
Warning: imagealphablending() expects parameter 1 to be resource, string given in ... on line 8
Warning: imagesx() expects parameter 1 to be resource, string given in ... on line 11
I tried adding imageCreateFromPng and header('Content-Type: image/png'); to the images but then I just get a empty page.

i don`t know what result were you want get , and i feel the page show is wrong . you can try run the program
<?php
header('Content-Type: image/png');
function image_mask(&$src, &$mask)
{
imagesavealpha($src, true);
imagealphablending($src, false);
// scan image pixels
// imagesx = get image width
for ($x = 0; $x < imagesx($src); $x++) {
// imagesy = get image height
for ($y = 0; $y < imagesy($src); $y++) {
$mask_pix = imagecolorat($mask,$x,$y);
//return r,g,b,alpha
$mask_pix_color = imagecolorsforindex($mask, $mask_pix);
if ($mask_pix_color['alpha'] < 127) {
$src_pix = imagecolorat($src,$x,$y);
$src_pix_array = imagecolorsforindex($src, $src_pix);
imagesetpixel($src, $x, $y, imagecolorallocatealpha($src, $src_pix_array['red'], $src_pix_array['green'], $src_pix_array['blue'], 127 - $mask_pix_color['alpha']));
}
}
}
}
$src = imagecreatefrompng('source.png');
$mask = imagecreatefrompng('mask.png');
image_mask($src, $mask);
imagepng($src);
imagedestroy($src);
imagedestroy($mask);
?>

“imagesavealpha() expects parameter 1 to be resource, string given”
the gaved param 1 of imagesavealpha is wrong,
it need resource,the resource may imagecreatetruecolor/imagecreatefrompng create

Related

realm react-native: how to query correctly an array of strings

can someone show me how to query an array of strings with realm in react-native?
assume i have an array like the following:
const preferences = ["automatic","suv","blue",eco]
What I want is to get realm results where ALL strings in the attribute "specifications" of Cars is in "preferences".
E.g.: If an instance of Cars.specifications contains ["automatic","suv"]
a result should be returned.
But if an instance of Cars.specifications contained ["automatic,"suv","green"] this instance shouldn't be returned.
The length of preferences can vary.
Thank you very much.
Update:
What i tried is the following:
const query = realm.objects("Cars").filtered('specifications = preferences[0] OR specifications = preferences[1]')
As you see it is an OR operator which is surely wrong and it is hardcoded. Looping with realm really confuses me.
This code will work!
const collection = realm.objects('Cars');
const preferences = ["automatic","suv","blue","eco"];
let queryString = 'ANY ';
for (let i = 0; i < preferences.length; i++) {
if (i === 0) {
queryString += `specifications CONTAINS '${preferences[i]}'`;
}
if (i !== 0 && i + 1 <= preferences.length) {
queryString += ` OR specifications CONTAINS '${preferences[i]}'`;
}
}
const matchedResult = collection.filtered(queryString);
example of function to test if a word is inside an array of word
function inArray(word, array) {
var lgth = array.length;
word = word.toLowerCase();
for (var i = 0; i < lgth; i++) {
array[i] = (array[i]).toLowerCase();
if (array[i] == word) return true;
}
return false;
}
const preferences = ["automatic","suv","blue","eco"];
const specifications = ["automatic","suv"] ;
const specifications2 = ["automatic","suv", "boat"] ;
function test(spec,pref){
for (var i in spec){
if(!inArray(spec[i],pref)){
return false ;
}
}
return true;
}
console.log(test(specifications,preferences));
console.log(test(specifications2,preferences));
https://jsfiddle.net/y1dz2gvu/

Calculating size of Google Firestore documents

Firestore docs give details of how to manually calculate the stored size of a document, but there does not seem to be a function provided for this on any of document reference, snapshot, or metadata.
Before I attempt to use my own calculation, does anyone know of an official or unofficial function for this?
Here is my (completely untested) first cut for such a function from my interpretation of the docs at https://firebase.google.com/docs/firestore/storage-size
function calcFirestoreDocSize(collectionName, docId, docObject) {
let docNameSize = encodedLength(collectionName) + 1 + 16
let docIdType = typeof(docId)
if(docIdType === 'string') {
docNameSize += encodedLength(docId) + 1
} else {
docNameSize += 8
}
let docSize = docNameSize + calcObjSize(docObject)
return docSize
}
function encodedLength(str) {
var len = str.length;
for (let i = str.length - 1; i >= 0; i--) {
var code = str.charCodeAt(i);
if (code > 0x7f && code <= 0x7ff) {
len++;
} else if (code > 0x7ff && code <= 0xffff) {
len += 2;
} if (code >= 0xDC00 && code <= 0xDFFF) {
i--;
}
}
return len;
}
function calcObjSize(obj) {
let key;
let size = 0;
let type = typeof obj;
if(!obj) {
return 1
} else if(type === 'number') {
return 8
} else if(type === 'string') {
return encodedLength(obj) + 1
} else if(type === 'boolean') {
return 1
} else if (obj instanceof Date) {
return 8
} else if(obj instanceof Array) {
for(let i = 0; i < obj.length; i++) {
size += calcObjSize(obj[i])
}
return size
} else if(type === 'object') {
for(key of Object.keys(obj)) {
size += encodedLength(key) + 1
size += calcObjSize(obj[key])
}
return size += 32
}
}
In Android, if you want to check the size of a document against the maximum of 1 MiB (1,048,576 bytes), there is a library that can help you with that:
https://github.com/alexmamo/FirestoreDocument-Android/tree/master/firestore-document
In this way, you'll be able to always stay below the limit. The algorithm behind this library is the one that is explained in the official documentation regarding the Storage Size.

Make OCG layer visible when field isn't empty?

Is it possible to check when a field is not empty and if not, make an ocg layer visible?
var ocg = FindOCG("Item 1 Arrow");
if (+event.value === '') {
ocg.state = !ocg.state;
} else {
ocg.state = !ocg.state;
}
Something like this (which doesn't work)!
Put this in the custom format script of the field in question. Replace "Square" with the name of your layer. You can see an example of it working here.
function getOCGByName(cName, nPage) {
var ocg = null;
var ocgArray = this.getOCGs(nPage);
for (var i=0; i < ocgArray.length; i++) {
if (ocgArray[i].name == cName) {
ocg = ocgArray[i];
}
}
return ocg;
}
var field = event.target;
var ocg = getOCGByName("Square", this.pageNum);
if (field.value.length > 0) {
ocg.state = true;
}
else {
ocg.state = false;
}
Note: This will only work in Adobe Acrobat and Reader and a few other viewers that are JavaScript capable.

if i upload image then edit work fine but if i update other field and not image that time it display array to sting erro in cakephp2.4.5

it will display error if i update other filed and not image.
public function edit($id = null) {
$this->helpers = array('TinyMCE.TinyMCE');
$this->layout = 'adminpanel';
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$this->layout = 'adminpanel';
//save data
if ($this->request->is(array('post', 'put'))) {
$this->Tour->id = $id;
//Save image
if(is_uploaded_file($this->request->data['Tour']['varbigimg']['tmp_name']))
{
$fileNameFull = $this->request->data['Tour']['varbigimg']['name'];
$uploadFolder = "upload";
//full path to upload folder
$uploadPath = WWW_ROOT . $uploadFolder;
$oldFile = $uploadPath.'/'.$fileNameFull;
move_uploaded_file(
$this->request->data['Tour']['varbigimg']['tmp_name'],$oldFile
);
$newFile = WWW_ROOT.'courseImages/thumb/'.$fileNameFull;
$image = new ImageResizeComponent();
$quality = 100; // image resize for thumb
$height = 40;
$width = 60;
$this->ImageResize->resize($oldFile, $newFile, 60,60,$quality);
$this->request->data['Tour']['varbigimg'] = $fileNameFull;
}
else{//Img not uploaded
$this->request->data['Tour']['vartitle']= $this->data['Tour']['vartitle'];
$this->request->data['Tour']['varsubtitle']= $this->data['Tour']['varsubtitle'];
$this->request->data['Tour']['txtsortdesc']= $this->data['Tour']['txtsortdesc'];
$this->request->data['Tour']['txtdeasc']= $this->data['Tour']['txtdeasc'];
$this->request->data['Tour']['vardeparts']= $this->data['Tour']['vardeparts'];
$this->request->data['Tour']['decadultprice']= $this->data['Tour']['decadultprice'];
$this->request->data['Tour']['decchildprice']= $this->data['Tour']['decchildprice'];
$this->request->data['Tour']['varimgtitle']= $this->data['Tour']['varimgtitle'];
$this->request->data['Tour']['enumstatus']= $this->data['Tour']['enumstatus'];
$this->request->data['Tour']['id']= $this->data['Tour']['id'];
//In this way do for All Except Image.
}
// pr($this->$this->request->data);
if ($this->Tour->save($this->request->data)) {
$this->Session->setFlash(__('Unable to add your schedule.'));
//Save image
$this->Session->setFlash(__('Your tour has been updated.'));
return $this->redirect(array('controller'=>'admin','action' => 'tour'));
$this->Session->setFlash(__('Unable to update your Tour.'));
}
}
$tour = $this->Tour->findByid($id);
if (!$tour) {
throw new NotFoundException(__('Invalid post'));
}
if (!$this->request->data) {
$this->request->data = $tour;
}
}
my cont code
my view is below. so when i upload image it will work fine. but in edit if i dont upload image then it display array to sting error. means it not take ast image. thanks
echo $this->Form->create('Tour',array('autocomplete' => 'off','enctype'=>'multipart/form-data'));
echo $this->Form->input('varbigimg',array('type' => 'file'));?>
Write Else for
if(is_uploaded_file($this->request->data['Tour']['varbigimg']['tmp_name']))
{
.........
}else{
//**TWO GOLDEN LINES OF YOUR LIFE**
$tourForImg = $this->Tour->findByid($id);
$this->request->data['Tour']['varbigimg'] = $tourForImg['Tour']['varbigimg'];
//**TWO GOLDEN LINES OF YOUR LIFE**
//AS Img not uploaded by user
//Write All data EXPLICITELY that you want to save WITHOUT Image.
$this->request->data['Tour']['Tourname']= $this->data['Tour']['Tourname'];
$this->request->data['Tour']['YourFormField1']= $this->data['Tour']['YourFormField1'];
$this->request->data['Tour']['YourFormField2']= $this->data['Tour']['YourFormField2'];
//In this way do for All Except Image.
}

Yii : Undefined variable: nama_unit_kerja

I need help. when i open my index it shows that the nama_unit_kerja variable is not defined..
But i've put them in the SiteController. How can i fix this.
This is my SiteController code :
public function actionIndex()
{
//$this->layout = "//layouts/adr/main";
/* $browser = Yii::app()->browser->isMobile();
echo ($browser?'mobile':'not mobile'); exit; */
#session_start();
Yii::app()->user->returnUrl = array('site/index');
$lang = 'en';
if(isset($_SESSION['lang'])) $lang = $_SESSION['lang'];
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->layout='//layouts/erp/index';
$modelUnitKerja=new UnitKerja('searchKapTarReal');
$modelUnitKerja->unsetAttributes(); // clear any default values
$modelJenisKegiatan=new JenisKegiatan('searchKapTarReal');
$modelJenisKegiatan->unsetAttributes(); // clear any default values
//var_dump($_POST);exit;
if ((isset($_POST['unitKerja'])) or (isset($_POST['year']))){
if(empty($_POST['unitKerja'])){
$unitKerja = 0;
} else {
$unitKerja = $_POST['unitKerja'];
$nama_unit_kerja = UnitKerja::model()->findByAttributes(array("id"=>$_POST['unitKerja']))->nama_unit_kerja;
}
$year = $_POST['year'];
$year_nm = Year::model()->findByAttributes(array("id"=>$_POST['year']))->year;
}else{
$unitKerja = 0;
$year = Year::model()->findByAttributes(array("year"=>date('Y')))->id;
$year_nm = date('Y');
}
$this->render('index',array(
'mJenisKegiatan'=>$modelJenisKegiatan,
'mUnitKerja'=>$modelUnitKerja,
'unitKerja'=>$unitKerja,
'nama_unit_kerja'=>$nama_unit_kerja,
'year'=>$year,
'year_nm'=>$year_nm,
));
}
$nama_unit_kerja = UnitKerja::model()->findByAttributes(array("id"=>$_POST['unitKerja']))->nama_unit_kerja;
hopefully you are getting this error on this line because you are trying to access the property of yii base.
you can use it like
$nama_unit_kerja = UnitKerja::model()->findByAttributes(array("id"=>$_POST['unitKerja']));
$nama_unit_kerja=$nama_unit_kerja->$nama_unit_kerja;