<?php
/*
ImageThumb - Creates a thumbnail image from another based on specified sizes
SourceImage - The location of the image in which you want to resize
DestImage - The location to save the thumb, use null if you want to just display to browser
Width - The resized width of the image
Height - The resized height of the image
Type - The image type in which you want to save
Note: The thumb is resized while keeping the aspect ratio, so width and height are not the
absolute width and height.
*/
function ImageThumb($sourceImage, $destImage, $width, $height, $type = "png") {
$type = strtolower($type);
$imageSize = getimagesize($sourceImage);
if($imageSize[0] > $imageSize[1]) {
$newWidth = $width;
$newHeight = $imageSize[1] * ($newWidth / $imageSize[0]);
}
else {
$newHeight = $height;
$newWidth = $imageSize[0] * ($newHeight / $imageSize[1]);
}
switch(image_type_to_mime_type($imageSize[2])) {
case "image/jpeg":
$image = imagecreatefromjpeg($sourceImage);
break;
case "image/gif":
$image = imagecreatefromgif($sourceImage);
break;
case "image/png":
$image = imagecreatefrompng($sourceImage);
break;
default:
$t = image_type_to_mime_type($imageSize[2]);
echo "The file type {$t} is not supported, please use either jpeg, gif, or png";
break;
}
$thumb = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($thumb, $image, 0, 0, 0, 0, $newWidth, $newHeight, $imageSize[0], $imageSize[1]);
switch($type) {
case "jpg":
case "jpeg":
header("Content-type: image/jpeg");
imagejpeg($thumb, $destImage);
break;
case "gif":
header("Content-type: image/gif");
imagegif($thumb, $destImage);
break;
case "png":
header("Content-type: image/png");
imagepng($thumb, $destImage);
break;
default:
echo "The image type {$type} is not supported, please choose another.";
break;
}
imagedestroy($image);
imagedestroy($thumb);
}
?>
Tag Archive for resize
Resize Image
Quickly resize images in command line (requires ImageMagick)
convert -resize WIDTHxHEIGHT source.jpg target.png
Mootools Draggable / Resize Example
function resizeDrag(){
//create an array of elements with class 'drag'
var draggables = $ES('.drag');
//For each of the above elements run this function(pass in the selected function el)
draggables.each(function(el){
//Make the element dragable. Draging starts on the element with class = handle
el.makeDraggable({handle: el.getElementsBySelector('.handle')[0]});
//Make the element resizable. Resizing starts on the element with class = resize
el.makeResizable({handle: el.getElementsBySelector('.resize')[0]});
});
}
Upload and resize with RMagick
require 'RMagick'
class Profile < ActiveRecord::Base
belongs_to :user
#image = the image passed from params[:image]
#file_type = the confirmed filetype from the controller
#current_user = various information about the current user
def self.upload(image, file_type, current_user)
#set default cols and rows for our two images that will be created from the uploaded user image
img_size = {:main =>{:cols => 250,:rows => 375},
:thumb =>{:cols =>80, :rows =>120}
}
#set base directory for the users image
imgDir = "#{RAILS_ROOT}/public/images/user_images"
#set the base name for our userimage
userImg = " #{current_user.login}-#{current_user.id}"
#loop through the image dir and delete any old user images
Dir.foreach(imgDir){|file|
if file.to_s.include?(userImg)
File.unlink("#{imgDir}/#{file}")
end
}
#read the image from the string
imgs = Magick::Image.from_blob(image.read)
#change the geometry of the image to suit our predefined size
main_image = imgs.first.change_geometry!("#{img_size[:main][:cols]}x#{img_size[:main][:rows]}") { |cols, rows, img|
#if the cols or rows are smaller then our predefined sizes we build a white background and center the image in it
if cols < img_size[:main][:cols] || rows < img_size[:main][:rows]
#resize our image
img.resize!(cols, rows)
#build the white background
bg = Magick::Image.new(img_size[:main][:cols],img_size[:main][:rows]){self.background_color = "white"}
#center the image on our new white background
bg.composite(img, Magick::CenterGravity, Magick::OverCompositeOp)
else
#in the unlikely event that the new geometry cols and rows match our predefined size we will not set a white bg
img.resize!(cols, rows)
end
}
main_image.write "#{imgDir}/#{userImg}.#{file_type}"
thumb = imgs.first.change_geometry!("#{img_size[:thumb][:cols]}x#{img_size[:thumb][:rows]}") { |cols, rows, img|
if cols < img_size[:thumb][:cols] || rows < img_size[:thumb][:rows]
img.resize!(cols, rows)
bg = Magick::Image.new(img_size[:thumb][:cols],img_size[:thumb][:rows]){self.background_color = "white"}
bg.composite(img, Magick::CenterGravity, Magick::OverCompositeOp)
else
img.resize!(cols, rows)
end
}
thumb.write "#{imgDir}/#{userImg}-thumb.#{file_type}"
if FileTest.exist?("#{imgDir}/#{userImg}.#{file_type}")
return "The file was written and its name is #{userImg}.#{file_type}"
else
return false
end
end
end
image resize dynamically
<?php
function imageResize($width, $height, $target) {
//takes the larger size of the width and height and applies the
formula accordingly...this is so this script will work
dynamically with any size image
if ($width > $height) {
$percentage = ($target / $width);
} else {
$percentage = ($target / $height);
}
//gets the new value and applies the percentage, then rounds the value
$width = round($width * $percentage);
$height = round($height * $percentage);
//returns the new sizes in html image tag format...this is so you
can plug this function inside an image tag and just get the
return "width="$width" height="$height"";
}
?>
//Then in the HTML:
<?php
//get the image size of the picture and load it into an array
$mysock = getimagesize("images/sock001.jpg");
?>
<!-using a standard html image tag, where you would have the
width and height, insert your new imageResize() function with
the correct attributes -->
<img src="images/sock001.jpg" <?php imageResize($mysock[0],
$mysock[1], 150); ?>>
Resize NSSplitView Nicely
- (void) splitView:(NSSplitView *)sender resizeSubviewsWithOldSize:(NSSize)oldSize {
// <a href="http://www.wodeveloper.com/omniLists/macosx-dev/2003/May/msg00261.html" >http://www.wodeveloper.com/omniLists/macosx-dev/2003/May/msg00261.html</a>
// grab the splitviews
NSView *left = [[sender subviews] objectAtIndex:0];
NSView *right = [[sender subviews] objectAtIndex:1];
float dividerThickness = [sender dividerThickness];
// get the different frames
NSRect newFrame = [sender frame];
NSRect leftFrame = [left frame];
NSRect rightFrame = [right frame];
// change in width for this redraw
int dWidth = newFrame.size.width - oldSize.width;
// ratio of the left frame width to the right used for resize speed when both panes are being resized
float rLeftRight = (leftFrame.size.width - MIN_LEFT_PANEL_W) / rightFrame.size.width;
// resize the height of the left
leftFrame.size.height = newFrame.size.height;
leftFrame.origin = NSMakePoint(0,0);
// resize the left & right pane equally if we are shrinking the frame
// resize the right pane only if we are increasing the frame
// when resizing lock at minimum width for the left panel
if(leftFrame.size.width <= MIN_LEFT_PANEL_W && dWidth < 0) {
rightFrame.size.width += dWidth;
} else if(dWidth > 0) {
rightFrame.size.width += dWidth;
} else {
leftFrame.size.width += dWidth * rLeftRight;
rightFrame.size.width += dWidth * (1 - rLeftRight);
}
rightFrame.size.width = newFrame.size.width - leftFrame.size.width - dividerThickness;
rightFrame.size.height = newFrame.size.height;
rightFrame.origin.x = leftFrame.size.width + dividerThickness;
[left setFrame:leftFrame];
[right setFrame:rightFrame];
}
PyS60 – Thread
import appuifw
import e32
import graphics
import thread
import time
class Main:
def __init__(self):
appuifw.app.title = u'Fibonacci'
appuifw.app.body = self.canvas = appuifw.Canvas()
appuifw.exit_key_handler = self.OnExit
appuifw.app.menu = [(u'Calcola', self.OnCalcola)]
self.nlock = thread.allocate_lock() # Allocazione di un lock per il thread
self.vlock = thread.allocate_lock()
self.ris1 = 0
self.ris2 = ''
self.loop = 1
self.indice = 0
self.img = graphics.Image.new(self.canvas.size)
self.OnLoop()
def OnCalcola(self):
numero = appuifw.query(u'Inserire un Numero', 'number')
thread.start_new_thread(self.fibonacci, (numero, ))
def fibonacci(self, n):
self.ris1 = time.strftime('%H:%M:%S')
self.ris2 = ''
a, b = 0, 1
for i in range(n):
a, b = b, a + b
self.nlock.acquire()
self.indice = ((i+1)*100)/n
self.nlock.release()
self.nlock.acquire()
self.ris2 = time.strftime('%H:%M:%S')
self.nlock.release()
def OnExit(self):
self.loop = 0
def OnLoop(self):
while self.loop:
e32.ao_sleep(0.1)
self.img.clear(0)
self.img.line([37, 50, 137, 50], 0xffffff, width=20)
self.img.line([37, 50, 37 + self.indice, 50], 0xfffc0d, width=20)
self.img.text((80, 55), u'' + str(self.indice) + u'%', 0x000000)
self.vlock.acquire()
if self.ris2 <> '':
self.img.text((45, 80), u'Start: ' + str(self.ris1), 0xffffff)
self.img.text((45, 92), u'End: ' + str(self.ris2), 0xffffff)
self.canvas.blit(self.img)
self.vlock.release()
if __name__ == '__main__':
main = Main()
Python – create attributes
class Demo: pass # Oggetto contenitore def createAttributes(): rc = Demo() setattr(rc, 'myobj', 'valore') return rc
Python – scrittura in unicode
import codecs
fp = codecs.open('E:demo.txt', 'w', 'utf_8')
fp.write('cioè')
fp.close()