Save current Google Map view as an image - image

I have a database with some addresses. For each address the view of the map will be different.
Is there a way, for each address, to save the map view as an image?

<img src='http://maps.googleapis.com/maps/api/staticmap?center=<?php echo
$MyAddress?>CA&zoom=14&size=500x500&markers=<?php echo $myAddress?>&sensor=false' alt=''/>
The center is where the map will be centered.
The markers is the address you want so i put center=markers.
Zoom is how close you want to zoom in the map
Size the size you want of the picture.
Take a look here
http://code.google.com/intl/el-GR/apis/maps/documentation/staticmaps/

In this case you can use the Google Static Maps API, from here.
For storage and bandwidth purposes you can only storage the GeoPoint of the location and only render the image when the user requests it.

public static function getGoogleMapImage($params = array(), $saveTo = null, $https = true){
//set default parameters
if(!isset($params['markers'])){
$params['center'] = isset($params['center']) ? $params['center'] : 0;
$params['zoom'] = isset($params['zoom']) ? $params['zoom'] : 0;
}
$params['size'] = isset($params['size']) ? $params['size'] : '200x200';
$params['sensor'] = isset($params['sensor']) ? $params['sensor'] : 'false';
foreach($params as $name => $value){
$paramString.=$name . '=' . urlencode($value) . '&';
}
$paramString = trim($paramString, '&');
$httpPrefix = $https ? 'https://' : 'http://';
$imageUrl = $httpPrefix . 'maps.googleapis.com/maps/api/staticmap?' . $paramString;
if(!$saveTo){ //if you don't want to save image, just to display it
return $imageUrl;
}
if(isset($params['format'])){
switch($params['format']){
case 'png8': $imgExt = '.png'; break;
case 'gif': $imgExt = '.gif'; break;
case 'jpg': $imgExt = '.jpg'; break;
case 'jpg-baseline': $imgExt = '.jpg'; break;
default: $imgExt = '.png';
}
}else{
$imgExt = '.png';
}
$saveTo = preg_replace("/\\.[^.\\s]{3,4}$/", "", $saveTo) . $imgExt; //in case requested file extension and provided in $saveTo don't match
if(self::getImage($imageUrl, $saveTo)){
return realpath($saveTo);
}
return false;
}
I used curl call for getting images from created $imageUrl

Related

How to display articles' image in Joomla search results

Is there a way to modify the code of the Joomla's search component so it can display even the article's image?
I have made a simple code that can search the image or youtube video in the article's text and return the media including the required tags as a string, but where do I put it?
// SEARCH IMAGE OR VIDEO
$hasImage = 0;
$hasVideo = 0;
$articleMedia = '';
$articleText = $text;
// has image?
preg_match_all('/<\s?img[^>]+\>/i', $articleText, $matches);
if(isset($matches['0']['0']))
{
$articleMedia = $matches['0']['0'] ;
$hasImage = 1;
}
// no image? maybe video
if ($hasImage == 0) {
preg_match_all('/(http:\/\/www\.youtube\.com\/watch\?v=([a-zA-Z0-9_-]+))/i', $articleText, $matches);
if(isset($matches['0']['0']))
{
$articleMediaID = $matches['2']['0'] ;
$articleMedia = "//www.youtube.com/embed/" . $articleMediaID;
$hasVideo = 1;
} else {
preg_match_all('/(http:\/\/youtu.be\/([a-zA-Z0-9_-]+))/i', $articleText, $matches1);
if( isset($matches1['0']['0']) ){
$articleMediaID = $matches1['2']['0'] ;
$articleMedia = "//www.youtube.com/embed/" . $articleMediaID;
$hasVideo = 1;
}
}
if ( $hasVideo == 1){
$articleMedia = '<iframe class="youtube" width="100%" src="' . $articleMedia . '" frameborder="0" allowfullscreen></iframe>';
}
}
// END SEARCH IMAGE OR VIDEO
You can create a search plugin, it's very simple to to create one, especially as you've worked out your core code already.
Depending on the type of Joomla search you're using you should read either:
Creating a Search Plugin
Creating a Smart Search Plugin

Magento hardcodes VARCHAR attributes to 255 length, any reason to not change this?

I have a requirement to save an Order Item attribute as a string up to 400 char. While it could be implemented using a text attribute, I would rather use a varchar(400). However, the _addFlatAttribute() method in Mage_Sales_Model_Resource_Setup hardcodes the length of varchar to 255. It could be changed after the fact by a setup script with DDL, but I'm wondering if there are likely to be downstream dependencies on VARCHAR being 255 char.
Any thoughts?
I believe that you will be fine & well-advised to do this given the ever-expanding size of order entity data in an instance. I'm curious what version of Magento though, as CE1.6+ is the first release to have the Mage_Sales_Model_Resource_Setup [link] class. Prior to CE1.6 the class was Mage_Sales_Model_Mysql4_Setup [link]. This is an important distinction because the column definition method in these classes differs to accomodate the DB-agnostic approach in 1.6+
Mage_Sales_Model_Mysql4_Setup::_getAttributeColumnDefinition [link]:
protected function _getAttributeColumnDefinition($code, $data)
{
$columnDefinition = '';
$type = isset($data['type']) ? $data['type'] : 'varchar';
$req = isset($data['required']) ? $data['required'] : false;
switch ($type) {
case 'int':
$columnDefinition = 'int(10) unsigned';
break;
case 'decimal':
$columnDefinition = 'decimal(12,4)';
break;
case 'text':
$columnDefinition = 'text';
break;
case 'date':
$columnDefinition = 'datetime';
break;
default:
$columnDefinition = 'varchar(255)';
break;
}
if ($req) {
$columnDefinition.= ' NOT NULL';
}
return $columnDefinition;
}
And Mage_Sales_Model_Resource_Setup::_getAttributeColumnDefinition [link]:
protected function _getAttributeColumnDefinition($code, $data)
{
// Convert attribute type to column info
$data['type'] = isset($data['type']) ? $data['type'] : 'varchar';
$type = null;
$length = null;
switch ($data['type']) {
case 'timestamp':
$type = Varien_Db_Ddl_Table::TYPE_TIMESTAMP;
break;
case 'datetime':
$type = Varien_Db_Ddl_Table::TYPE_DATETIME;
break;
case 'decimal':
$type = Varien_Db_Ddl_Table::TYPE_DECIMAL;
$length = '12,4';
break;
case 'int':
$type = Varien_Db_Ddl_Table::TYPE_INTEGER;
break;
case 'text':
$type = Varien_Db_Ddl_Table::TYPE_TEXT;
$length = 65536;
break;
case 'char':
case 'varchar':
$type = Varien_Db_Ddl_Table::TYPE_TEXT;
$length = 255;
break;
}
if ($type !== null) {
$data['type'] = $type;
$data['length'] = $length;
}
$data['nullable'] = isset($data['required']) ? !$data['required'] : true;
$data['comment'] = isset($data['comment']) ? $data['comment'] : ucwords(str_replace('_', ' ', $code));
return $data;
}
I can't imagine so, it might be different if you were to decrease the size of varchar, though.
See also:
Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?
Use type TEXT instead of VARCHAR. Mage_Sales_Model_Resource_Setup assumes a length of 64KB in this case.

How resize image in Joomla?

I try use this:
$image = new JImage();
$image->loadFile($item->logo);
$image->resize('208', '125');
$properties = JImage::getImageFileProperties($item->logo);
echo $image->toFile(JPATH_CACHE . DS . $item->logo, $properties->type);
But not work =\ any idea?
Try this out:
// Set the path to the file
$file = '/Absolute/Path/To/File';
// Instantiate our JImage object
$image = new JImage($file);
// Get the file's properties
$properties = JImage::getImageFileProperties($file);
// Declare the size of our new image
$width = 100;
$height = 100;
// Resize the file as a new object
$resizedImage = $image->resize($width, $height, true);
// Determine the MIME of the original file to get the proper type for output
$mime = $properties->mime;
if ($mime == 'image/jpeg')
{
$type = IMAGETYPE_JPEG;
}
elseif ($mime == 'image/png')
{
$type = IMAGETYPE_PNG;
}
elseif ($mime == 'image/gif')
{
$type = IMAGETYPE_GIF;
}
// Store the resized image to a new file
$resizedImage->toFile('/Absolute/Path/To/New/File', $type);

CodeIgniter Upload and Resize Problem

I have spent days trying to make this work based on the examples in the documentation but I am missing something or I am just STUPID!
I have a CMS application where users upload an image for display in a very fixed layout. We do not want to limit the file size of the uploaded image but would rather "process" it after it arrives.
The image needs to be 615px wide but some of the images uploaded directly from digital cameras are 2500X2000 and bigger so this is CRITICAL.
I pieced together the code from the manual and the image is successfully being uploaded to a folder within the CMS app. However, the image is NOT being resized.
If I ever get it to re-size, my plan is to present the image to the user for cropping using jCrop (the final image HAS to be 615X275 and it probably has to be cropped for height after resizing) and then use codeigniter to FTP the image to their site's amenities folder using the original name.
I will appreciate any help in this matter!
Here's my code:
function do_feature_upload() {
$imageName = $this->uri->segment(3);
//echo $imageName;
// Where the file is going to be placed
$config['upload_path'] = "./uploads/".$_SESSION['dbPropNumber'];
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = '0';
$config['file_name'] = $imageName.'.jpg';
$config['overwrite'] = 'TRUE';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$error['propertyDropdown'] = $_SESSION['propertyDropdown'];
$error['username'] = $_SESSION['username'];
$error['dbPropNumber'] = $_SESSION['dbPropNumber'];
$error['propertyName'] = $this->content->getPropertyName($_SESSION['dbPropNumber']);
$this->load->view('upload_AmenityImage', $error);
} else {
$image_data = $this->upload->data();
$origWidth = $image_data['image_width'];
$origHeight = $image_data['image_height'];
$newWidth = 615;
$newHeight = $newWidth*$origHeight/$origWidth;
$resize = array(
'image_library'=>'gd2',
'source_image'=>base_url().'uploads/'.$_SESSION['dbPropNumber'].'/'.$imageName.'.jpg',
'new_image'=>base_url().'uploads/'.$_SESSION['dbPropNumber'].'/'.$imageName.'1.jpg',
'create_thumb' => FALSE,
'maintain_ratio'=>FALSE,
'width'=>$newWidth,
'height'=>$newHeight
);
$this->load->library('image_lib',$resize);
$this->image_lib->resize();
$data = array('upload_data' => $this->upload->data());
$data['propertyDropdown'] = $_SESSION['propertyDropdown'];
$data['username'] = $_SESSION['username'];
$data['dbPropNumber'] = $_SESSION['dbPropNumber'];
$data['propertyName'] = $this->content->getPropertyName($_SESSION['dbPropNumber']);
//Present jCrop option after image is resized
// FTP to final destination
$this->load->view('upload_success', $data);
} // end if
} // end function
I'm not entirely sure what's going wrong with your code, but here's a model function I wrote for resizing images to fit an exact target height and target width. Read through it and see if you can't figure out the solution.
$this->prefix is a property in my class that I use so I don't have to keep writing out the directory of the file. It looks like this:
$this->prefix = FCPATH.'uploads'.DIRECTORY_SEPARATOR;
Image resizer
/**
* Resizes an image to fit exact dimensions
*
* #param string filename
* #param int target_width
* #param int target_height
*
* #return array('success' ? null : 'error')
*/
function resizeImageToDimensions($filename, $target_width=700, $target_height=399)
{
$file_type = $this->getFileType($this->prefix.$filename);
if (!$file_type || $file_type != 'image')
return array('success'=>false, 'error'=>"This file doesn't exist or isn't an image");
$this->load->library('image_lib');
list($width, $height) = getimagesize($this->prefix.$filename);
$current_ratio = $width/$height;
$target_ratio = $target_width/$target_height;
$config['source_image'] = $this->prefix.$filename;
if ($current_ratio > $target_ratio)
{
//resize first to height, maintain ratio
$config['height'] = $target_height;
$config['width'] = $target_height * $current_ratio;
$this->image_lib->initialize($config);
if (!$this->image_lib->resize())
return array('success'=>false, 'error'=>"There was an error while resizing this image");
//then crop off width
$config['width'] = $target_width;
$config['maintain_ratio'] = false;
$this->image_lib->initialize($config);
if ($this->image_lib->crop())
return array('success'=>true);
else
return array('success'=>false, 'error'=>"There was an error while cropping this image");
}
else if ($current_ratio < $target_ratio)
{
//resize first to width, maintain ratio
$config['width'] = $target_width;
$config['height'] = $target_width / $current_ratio;
$this->image_lib->initialize($config);
if (!$this->image_lib->resize())
return array('success'=>false, 'error'=>"There was an error while resizing this image");
//then crop off height
$config['height'] = $target_height;
$config['maintain_ratio'] = false;
$this->image_lib->initialize($config);
if ($this->image_lib->crop())
return array('success'=>true);
else
return array('success'=>false, 'error'=>"There was an error while cropping this image");
}
else {
$config['width'] = $target_width;
$config['height'] = $target_height;
$this->image_lib->initialize($config);
if ($this->image_lib->resize())
return array('success'=>true);
else
return array('success'=>false, 'error'=>"There was an error while resizing this image");
}
}
I had the same problem a few months back and sadly, I wasn't able to figure it out. I've posted the same question here and in CodeIgniter's forums but no one could help me.
I ended up using timthumb script, which is great, but nowhere near ideal :(
So, if you're in a rush, I'd strongly recommend using timthumb. If you have some time to invest on it, I wish you the best and please, share!

How can I modify this image manipulation function done in codeigniter to be more efficient

I think this function isn't as efficient as it should be. I'd appreciate some suggestions on how I can structure it to be faster and take less memory. This is what the code does:
checks to see if the image was uploaded
add details about it (tags, name, details) to the database
if the variable $orientation was set, rotate the image
if the image is wider than 600px, resize it
create a thumbnail
I think the inefficiencies come from having steps 3,4,5 all separate. Is there any way to consolidate them? Thanks!
function insert()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg';
$config['max_size'] = '5000';
$config['max_width'] = '4096';
$config['max_height'] = '4096';
$this->load->library('upload', $config);
if (!$this->upload->do_upload())
{
$data = array('error' => $this->upload->display_errors());
$data['title'] = "Add Photo | Mark The Dark";
$this->load->view('photo_add_view', $data);
}
else
{
//get uploaded image info
$data = array('upload_data' => $this->upload->data());
//clean the data
$data = $this->input->xss_clean($data);
//get orientation info and erase it from POST variable
//$orientation = $_POST['orientation'];
//unset($_POST['orientation']);
//grab the tags
$tags = $_POST['tags'];
unset($_POST['tags']);
//add in some other stuff
$_POST['time'] = date('YmdHis');
$_POST['author'] = $this->dx_auth->get_user_id();
//insert it in the database
$this->db->insert('photos', $_POST);
$photo_id = $this->db->insert_id();
//add stuff to tags table
/*
$tags_array = preg_split('/[\s,;]+/', $tags);
foreach($tags_array as $tag)
{
if($tag != "" || $tag != null)
$this->db->insert('tags', array('id' => $photo_id, 'word' => $tag));
}*/
//CXtags
/*$tags_array = preg_split('/[\s,;]+/', $tags);
foreach($tags_array as $tag)
{
if($tag == "" || $tag == null)
{unset($tags_array[$tag]);}
}
*/
$tags_array = $this->CXTags->comma_to_array($tags);
foreach($tags_array as $tag)
{$tags_array[$tag] = $this->CXTags->make_safe_tag($tag);}
$topass = array(
'table' => 'photos',
'tags' => $tags_array,
'row_id' => $photo_id,
'user_id' => $_POST['author']
);
$this->CXTags->add_tags($topass);
//rename the file to the id of the record in the database
rename("./uploads/" . $data['upload_data']['file_name'], "./uploads/" . $photo_id . ".jpg");
list($width, $height, $type, $attr) = getimagesize("./uploads/" . $photo_id . '.jpg');
if (($orientation == 1) || ($orientation == 2))
{
//echo $orientation;
//rotate image
$config['image_library'] = 'GD2';
$config['source_image'] = './uploads/' . $photo_id . '.jpg';
if ($orientation == 1)
{
$config['rotation_angle'] = 270;
}
elseif ($orientation == 2)
{
$config['rotation_angle'] = 90;
}
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
if(!$this->image_lib->rotate())
{
echo $this->image_lib->display_errors();
}
}
$this->load->library('image_lib');
if ($width > 600)
{
//resize image
$config['image_library'] = 'GD2';
$config['source_image'] = './uploads/' . $photo_id . '.jpg';
$config['new_image'] = './uploads/photos/' . $photo_id . '.jpg';
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 600;//180
$config['height'] = 480;
$config['master_dim'] = 'width';
$this->image_lib->initialize($config);
$this->load->library('image_lib', $config);
if(!$this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
}
else
{
$source = './uploads/' . $photo_id . '.jpg';
$destination = './uploads/photos/' . $photo_id . '.jpg';
rename($source, $destination);
/*//buggy php???
$result = copy($source, $destination);
echo "HO" . $result;
*/
}
//create thumbnail
$config['image_library'] = 'GD2';
$config['source_image'] = './uploads/photos/' . $photo_id . '.jpg';
$config['new_image'] = './uploads/thumbnails/' . $photo_id . '.jpg';
$config['create_thumb'] = TRUE;
$config['thumb_marker'] = '_thumb';
$config['maintain_ratio'] = TRUE;
$config['width'] = 180;//180
$config['height'] = 100;
$config['master_dim'] = 'width';
$this->image_lib->initialize($config);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
redirect('photo/show/' . $photo_id);
}
//redirect('photo/photo_add/');
}
Well, I can answer part of your question - you can rotate images which carry the exif rotation using Codeigniter.
Firstly:
Detect the uploaded images exif data.
Look at the $exif array and handle the Orientation item.
Pass the required rotation degrees to codeigniters image_lib->rotate() function.
EG:
public function auto_rotate_image($upload_data){//iphone rotation fix
$path = $upload_data['full_path'];
$exif = exif_read_data($path);
if(isset($exif['Orientation'])){
$rotate = false;
switch($exif['Orientation']){//only really interested in the rotation
case 1: // nothing
break;
case 2:// horizontal flip
break;
case 3: // 180 rotate left
$rotate = 180;
break;
case 4: // vertical flip
break;
case 5: // vertical flip + 90 rotate right
break;
case 6: // 90 rotate right
$rotate = 270;
break;
case 7: // horizontal flip + 90 rotate right
break;
case 8: // 90 rotate left
$rotate = 90;
break;
}
if($rotate){
$config=array();
$config['image_library'] = 'gd2';
$config['source_image'] = $path;
$config['rotation_angle'] = $rotate;
$config['overwrite'] = TRUE;
$this->load->library('image_lib',$config);
if(!$this->image_lib->rotate()){
echo $this->image_lib->display_errors();
}
}
}
}
For all the work required to do your image manipulation using the objects that code igniter exposes for you, you may want to look into doing this yourself strictly with the gd functions in php. I have not used code igniter, but I've done a lot of stuff with image manipulation in php, and it's not terribly difficult.
Just by looking at your code, and I'm assuming this is the code igniter way, I see you calling image_lib->initialize() and load->library() for each individual manipulation. I'd have a look inside those methods and the rotate() and resize() methods you're using and see if they're creating and destroying the image resource with each manipulation. If you use the gd library, you can reuse the same image resource for each step and then just write it to file when you're ready (re-use the same image resource to create the thumbnail). This would probably make a huge performance gain in both execution speed and memory used.
GD Functions in PHP
You could store your configs elsewhere per codeigniter documentation, that would tighten the code up. I don't know how you could chain those events.

Resources