Kohana 3.1 create imagejpeg or imagepng captcha - captcha

Im trying to put a simple captcha in kohana 3.1 using the following code to generate for me the image from a model.
$session = Session::instance();
$string = '';
for ($i = 0; $i < 5; $i++) {
$string .= chr(rand(97, 122));
}
$cns_captcha = $session->set('random_number', $string);
$dir = LIBPATH.'fonts/';
$image = imagecreatetruecolor(165, 50);
// random number 1 or 2
$num = rand(1,2);
if($num==1)
{
$font = "Capture it 2.ttf"; // font style
}
else
{
$font = "Molot.otf";// font style
}
// random number 1 or 2
$num2 = rand(1,2);
if($num2==1)
{
$color = imagecolorallocate($image, 113, 193, 217);// color
}
else
{
$color = imagecolorallocate($image, 163, 197, 82);// color
}
$white = imagecolorallocate($image, 255, 255, 255); // background color white
imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, $dir.$font, $cns_captcha);
//header('Content-Type: image/PNG');
imagepng($image);
unfortunately this is producing
�PNG IHDR�2�*�v�IDATx���o�d���4��4oM�Ѵe�&�)�F��NCCB���� � q�i�� qp��6M�0�S�/����]����ͱ�C�4t��؎�D��d�y��_?�����G�x�À��
and no image
thanks in advance for your assistance.

You dont set the content type, your browser assumes it is text.
imagettftext ($image, 30, 0, 10, 40, $color, $dir.$font, $cns_captcha);
$this->response->headers('Content-Type', 'image/png');
imagepng($image);
EDIT:
as a sidenote, have you looked at Kohana's image module? http://kohanaframework.org/3.3/guide-api/Image

Related

Print value of an array using three.js TextGeomtery

How can I print the values of an array using three.js textGeometry. Trying the following code but no output.
`for(let i=0;i<=4;i++)
{
let arr = [1,2,3,4,5,6,7,8];
let char = arr[i];
let loader = new THREE.FontLoader();
let font = loader.parse(fontJSON);
let geometry = new THREE.TextBufferGeometry(char ,{font : font , size : 1 , height : 0.1 });
let material = new THREE.MeshBasicMaterial({ color : 0xffffff });
let text = new THREE.Mesh(geometry , material);
text.position.set(i,0,0);
scene.add(text);
}`
You have to make sure to provide a string to TextBufferGeometry, no number. You can easily ensure this by calling toString() on your char variable. I've refactored your code a bit to show you a complete example.
let camera, scene, renderer;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
camera.position.z = 8;
scene = new THREE.Scene();
const material = new THREE.MeshBasicMaterial({
color: 0xffffff
});
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const loader = new THREE.FontLoader();
loader.load('https://threejs.org/examples/fonts/helvetiker_regular.typeface.json', (font) => {
for (let i = 0; i <= 4; i++) {
const char = arr[i];
const geometry = new THREE.TextBufferGeometry(char.toString(), {
font: font,
size: 1,
height: 0.1
});
const text = new THREE.Mesh(geometry, material);
text.position.set(i, 0, 0);
scene.add(text);
}
});
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
body {
margin: 0;
}
canvas {
display: block;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.117.1/build/three.js"></script>

How to resize image yii2 when uploading

This is my post controller function. I always upload images less then 200x200, and those images are stored in the 'upload' folder. After uploading the image, the id number is changed to something like 4546464.png. But I want to change the image size to 60x60 when uploading and store it after changing the size and quality to 60x60x30. This code uploads fine but not changing size and quality.
public function actionCreate() {
$model = new Monitor();
if ($model->load(Yii::$app->request->post())) {
if ($model->payment_processor) {
$model->payment_processor = implode(',', $model>payment_processor);
}
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->file != '') {
$model->image = time() . '.' . $model->file->extension;
}
$model->update_at = date('Y-m-d h:i:s');
$model->save();
if ($model->file != '') {
$model->file->saveAs('upload/' . $model->image);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', ['model' => $model]);
}
}
, you have to first upload the image in your server then resize it to what size you want , another way is before you
$model->file->saveAs('upload/' . $model->image);
resize it , but i recommend to you save the Original file and then resize it as a copy.
here is function to resize and crop image from center :
public static function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 100){
$quality = 10;
$imgsize = getimagesize($source_file);
$width = $imgsize[0];
$height = $imgsize[1];
$mime = $imgsize['mime'];
switch($mime){
case 'image/gif':
$image_create = "imagecreatefromgif";
$image = "imagegif";
break;
case 'image/png':
$image_create = "imagecreatefrompng";
$image = "imagepng";
$quality = 9;
break;
case 'image/jpeg':
$image_create = "imagecreatefromjpeg";
$image = "imagejpeg";
$quality = 100;
break;
default:
return false;
break;
}
$dst_img = imagecreatetruecolor($max_width, $max_height);
$src_img = $image_create($source_file);
$width_new = $height * $max_width / $max_height;
$height_new = $width * $max_height / $max_width;
//if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
if($width_new > $width){
//cut point by height
$h_point = (($height - $height_new) / 2);
//copy image
imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
}else{
//cut point by width
$w_point = (($width - $width_new) / 2);
imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
}
$image($dst_img, $dst_dir, $quality);
if($dst_img)imagedestroy($dst_img);
if($src_img)imagedestroy($src_img);
}
use this function as easy you can :
yourModel::resize_crop_image(150,150, $path, 'upload/'.$name_you_want_or_random_string.'.jpg',$q);
the $path is a path of the original file that uploaded .
you have to create a upload folder in your web app directory or change destination to where you want .
I am using the imageprocessor extension and I'm very happy with it. You just have to add confgurations to the imageprocessor component and on save you have to call the save method of the component. It will create a new image with the size you've configured. It has a nice documentation. Give it a try.

ActionScript 2 following a path

I am having a problem finding information on using actionscript 2 to move an object along a more complicated path. I have no issue if i need to tween in the x or y direction, or at the same time, but If i wanted an object to follow a curvy path could someone provide me sample code for a way to follow a motion guide or a curved path like a bezier?
here is my usual code:
Tween1();
function Tween1(){
setTimeout(theTween, 0);
function theTween(){
var myTween:Tween = new Tween(Object, "_x", Regular.easeOut, 0, 100, 1, true);
var myTween:Tween = new Tween(Object, "_y", Regular.easeOut, 0, 100, 1, true);
}
try this Animate along bezier curve
var circle:Shape = Shape(addChild(new Shape));
with(circle.graphics) beginFill(0x000000), drawCircle(0,0,5);
var bezierPoint:Point = new Point();
function bezier(a:Number, x1:Number, y1:Number, x2:Number, y2:Number, x3:Number, y3:Number):void {
var b:Number =1-a;
var pre1:Number=a*a;
var pre2:Number=2*a*b;
var pre3:Number=b*b;
bezierPoint.x = pre1*x1 + pre2*x2 + pre3*x3;
bezierPoint.y = pre1*y1 + pre2*y2 + pre3*y3;
}
var inc:Number = 0;
var theta:Number = 0;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
graphics.clear();
graphics.lineStyle(0,0xFF0000);
graphics.moveTo(200,200);
graphics.curveTo(mouseX, mouseY, 400, 200);
inc += .03;
inc %= 1;
bezier(inc, 200, 200, mouseX, mouseY, 400, 200);
circle.x = bezierPoint.x;
circle.y = bezierPoint.y;
}

Auto suggest dropdown in titanium example?

I am able to implement auto suggest drop down in jquery .Now I am implementing a same functionality in titanium but when i googled I don't found much in autosuggestion
drop down in titanium .
can you suggest a way of autogestion.
Mean I have a array (element).When I click on textfield it show related element.
Try the following code and modify as per your need. Here I Used array(searchArray) as data storage(You can replace it with database field or source whatever as per your requirement).
//Table view showing your autocomplete values
var tblvAutoComplete = Ti.UI.createTableView({
width : '100%',
backgroundColor : '#EFEFEF',
height : 0,
maxRowHeight : 35,
minRowHeight : 35,
allowSelection : true
});
//Starts auto complete
txtAutoComplete.addEventListener('change', function(e){
var pattern = e.source.value;
var tempArray = PatternMatch(searchArray, pattern);
CreateAutoCompleteList(tempArray);
});
//You got the required value and you clicks the word
tblvAutoComplete.addEventListener('click', function(e){
txtAutoComplete.value = e.rowData.result;
});
//Returns the array which contains a match with the pattern
function PatternMatch(arrayToSearch, pattern){
var searchLen = pattern.length;
arrayToSearch.sort();
var tempArray = [];
for(var index = 0, len = arrayToSearch.length; index< len; index++){
if(arrayToSearch[index].substring(0,searchLen).toUpperCase() === pattern.toUpperCase()){
tempArray.push(arrayToSearch[index]);
}
}
return tempArray;
}
//setting the tableview values
function CreateAutoCompleteList(searchResults){
var tableData = [];
for(var index=0, len = searchResults.length; index < len; index++){
var lblSearchResult = Ti.UI.createLabel({
top : 2,
width : '40%',
height : 34,
left : '5%',
font : { fontSize : 14 },
color : '#000000',
text : searchResults[index]
});
//Creating the table view row
var row = Ti.UI.createTableViewRow({
backgroundColor : 'transparent',
focusable : true,
height : 50,
result : searchResults[index]
});
row.add(lblSearchResult);
tableData.push(row);
}
tblvAutoComplete.setData(tableData);
tblvAutoComplete.height = tableData.length * 35;
}
This code worked for me in both ios and android. Hope your problems get resolved:D

gd library - font size?

I am creating a captcha image (please do not suggest premade ones).
It gives you the ability to call
$captcha = new captcha();
$captcha->size(30)->getImage();
which sets the font size to 30 and then generates the captcha.
my issue is with sizing.
How can I work out how wide the image should be?
the captcha has 6 characters.
I thought I could just do ($size*6)+10 to make the image wide enough + give it a 5px padding on each side (text is centered), but apparently not.
Code
<?php
session_start();
class captcha {
private $font = 'monofont.ttf';
private $characters = '23456789bcdfghjkmnpqrstvwxyz';
private $size = 30;
private $count = 6;
private $colors = array(
'b' => array('r' => 0, 'g' => 0, 'b' => 0),
't' => array('r' => 200, 'g' => 200, 'b' => 200),
'n' => array('r' => 127, 'g' => 127, 'b' => 127)
);
function count($count) {
$this->count = $count;
return $this;
}
function size($size){
$this->size = $size;
return $this;
}
function characters($characters) {
$this->characters = $characters;
return $this;
}
function backgroundColor($red, $green, $blue){
$this->colors['b']['r'] = $red;
$this->colors['b']['g'] = $green;
$this->colors['b']['b'] = $blue;
return $this;
}
function noiseColor($red, $green, $blue){
$this->colors['n']['r'] = $red;
$this->colors['n']['g'] = $green;
$this->colors['n']['b'] = $blue;
return $this;
}
function textColor($red, $green, $blue){
$this->colors['t']['r'] = $red;
$this->colors['t']['g'] = $green;
$this->colors['t']['b'] = $blue;
return $this;
}
function generateCode() {
$code = '';
$i = 0;
while ($i < $this->count) {
$code .= strtoupper(substr($this->characters, mt_rand(0, strlen($this->characters) - 1), 1));
$i++;
}
return $code;
}
function getWidth() {
return ($this->count * $this->size);
}
function getHeight() {
return $this->size+10;
}
function getCaptcha() {
$code = $this->generateCode();
$this->width = $this->getWidth();
$this->height = $this->getHeight();
$image = #imagecreate($this->width, $this->height) or die('Cannot initialize new GD image stream');
//define colors
$tColor = imagecolorallocate($image, $this->colors['t']['r'], $this->colors['t']['g'], $this->colors['t']['b']);
$nColor = imagecolorallocate($image, $this->colors['n']['r'], $this->colors['n']['g'], $this->colors['n']['b']);
$bColor = imagecolorallocate($image, $this->colors['b']['r'], $this->colors['b']['g'], $this->colors['b']['b']);
//fill image
imagefill($image, 0, 0, $bColor);
/* generate random dots in background */
for ($i = 0; $i < ($this->width * $this->height) / 3; $i++) {
imagefilledellipse($image, mt_rand(0, $this->width), mt_rand(0, $this->height), 1, 1, $nColor);
}
/* generate random lines in background */
for ($i = 0; $i < ($this->width * $this->height) / 150; $i++) {
imageline($image, mt_rand(0, $this->width), mt_rand(0, $this->height), mt_rand(0, $this->width), mt_rand(0, $this->height), $nColor);
}
/* create textbox and add text */
$textbox = imagettfbbox($this->size, 0, $this->font, $code) or die('Error in imagettfbbox function');
$x = ($this->width - $textbox[4]) / 2;
$y = ($this->height - $textbox[5]) / 2;
imagettftext($image, $this->size, 0, $x, $y, $tColor, $this->font, $code) or die('Error in imagettftext function');
//imagefilter($image, IMG_FILTER_NEGATE);
imagefilter($image, IMG_FILTER_SMOOTH, 1);
/* output captcha image to browser */
header('Content-Type: image/jpeg');
header('Cache-Control: no-cache, must-revalidate');
imagejpeg($image);
imagedestroy($image);
$_SESSION['security_code'] = $code;
}
}
$captcha = new captcha();
$captcha->size(30)->count(6)->getCaptcha();
?>
You can use imagegetttfbbox() to determine the bounding box which can contain your string. But since you're generating a captcha, which means the characters are highly distored, I don't think it'd particularly accurate. It's intended for regular un-altered text.