mercoledì 14 marzo 2018

Resize image e rotate image in php prima di eseguire un update su MySql

Immaginiamo un form in php con un'immagine da uploadare su db Mysql e la vogliamo ridimensionare e ruotare prima di inserirla o aggiornarla.
Ecco un esempio di codice php per aggiornare una tabella in un database con un'immagine ridimensionata e ruotata a 90 gradi:
$pdo = Database::connect();
$idArticle=$_POST["idart"];

$query = "SELECT Image FROM Table WHERE Id=?"; 
try{
 $pdo_statement = $pdo->prepare($query);
 $pdo_statement->bindParam(1,$idArticle );
 $pdo_statement->execute();
 
 $num = $pdo_statement->rowCount();

 if ($num) {
  $row = $pdo_statement->fetch(PDO::FETCH_ASSOC);
  if($row['Image']!=null){
   $image = imagecreatefromstring($row['Image']);
   $w = imagesx($image);
   $h = imagesy($image);
   
   //resize image
   $ratio=0.5;
   $larg = $w/$ratio;
   $alt = $h/$ratio;
   $image = imagescale($image, $larg, $alt);
   
   ob_start();
   
   //rotate image
   $transp = imagecolorallocatealpha($image,0,0,0,127 );
   $image  = imagerotate($image, 90, $transp, 1);
   
   imagejpeg($image);

   $contents = ob_get_contents();
   ob_end_clean();

   imagedestroy($image);

   $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
   $sql = "UPDATE Table set Image=? WHERE Id=?";
   $pdo = $pdo->prepare($sql);
   $pdo->bindParam(1, $contents, PDO::PARAM_LOB);
   $pdo->bindParam(2, $idArticle);

   $pdo->execute();
   
   echo " img src='data:image/jpeg;base64,".base64_encode($contents)."' / ";
  }
 }else{
  return null;
 }
}catch(PDOException $e) 
{
 echo $e->getMessage();
}

Database::disconnect();

venerdì 9 marzo 2018

Chiamare un web service in modalità asincrona e sincrona in c#

Il seguente esempio è una chiamata ad un metodo di un web service in c# con una risposta in modalità sincrona o asincrona.

Decommentando la parte di wait response si potrà attendere l'esito, altrimenti verrà restituito un risultato mentre l'elaborazione sarà in corso.
public class ServiceExample : System.Web.Services.WebService
    {
 private delegate string AsyncMethodCallerCreateZip(string idArticle, out string outResult);
  
 [WebMethod(Description = "An example")]
 public string FirstElaboration(string idArticle)
 {
  try
  {
   //Async call
   AsyncMethodCallerCreateZip caller = new AsyncMethodCallerCreateZip(CreateZip);
   IAsyncResult result = caller.BeginInvoke(idArticle, out outResult, null, null);

   //wait response
   //result.AsyncWaitHandle.WaitOne();
   //string returnValue = caller.EndInvoke(out outResult, result);
   //result.AsyncWaitHandle.Close();
   //return returnValue;

   return "OK";
  }
  catch (Exception ex)
  {
   return "KO";
  }
 }

 public string CreateZip(string idArticle, out string outResp)
 {
  //code here
  return outResp;
 }
}