Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 58 total  RSS 

Generate a graph using Gruff

This Ruby code produced a graph using gruff. The output shows a line graph [twitxr.com] for the different fruits. Source code origin: Gruff Update With Bar Graphs | Ruby on Rails for Newbies [rubyonrails.com]

require 'gruff'

g = Gruff::Line.new
g.title = "My Graph" 

g.data("Apples", [1, 2, 3, 4, 4, 3])
g.data("Oranges", [4, 8, 7, 9, 8, 9])
g.data("Watermelon", [2, 3, 1, 5, 6, 8])
g.data("Peaches", [9, 9, 10, 8, 7, 9])

g.labels = {0 => '2003', 2 => '2004', 4 => '2005'}

g.write('my_fruity_graph.png')


Note: I executed the code within an irb session on my Gentoo box. With Gentoo, Gruff was installed [gentoo-portage.com] using the command emerge -va gruff. I tried installing it on Ubuntu but ran into some difficulty, even with help from the article install rmagick ubuntu [dzone.com].

*udpate 21:48 24-Feb*

The following code does exactly as the same code above, however it uses XML to separate the data from the process, making it easier and more efficient to build graphs.
#!/usr/bin/ruby
# file: xml2gruff.rb

require 'rexml/document'
require 'gruff'
include REXML

class Xml2Gruff
  
  def initialize(filename)
    file = File.new(filename, 'r')
    doc = Document.new(file)
    # get the title
    @title = doc.root.elements['summary/title'].text
    
    @record = Hash.new
    # get each record
    doc.root.elements.each('records/item') {|item|
      avalues = Array.new
      item.elements.each('values/value') { |value| avalues << value.text.to_i }
      @record[item.elements['label'].text] = avalues
    }
    
    # get the summary labels
    @labels = Hash.new  
    doc.root.elements.each('summary/scale/label') {|l| @labels[l.elements['value'].text.to_i] = l.elements['title'].text} 
    
  end
  
  def save_line_graph(filename)

    g = Gruff::Line.new
    g.title = @title 
    @record.each {|label, data| g.data(label, data) }
    g.labels = @labels
    g.write(filename)

  end
end

if __FILE__ == $0
 x2g = Xml2Gruff.new('my_fruit.xml')
 x2g.save_line_graph('my_fruit2.png')
end


file: my_fruit.xml
<graph>
  <summary>
    <title>My Graph</title>
    <scale>
      <label><title>2003</title><value>0</value></label>
      <label><title>2004</title><value>2</value></label>
      <label><title>2005</title><value>4</value></label>
    </scale>
  </summary>
  <records>
    <item>
      <label>Apples</label>
      <values><value>1</value><value>2</value><value>3</value><value>4</value><value>4</value><value>3</value></values>
    </item>
    <item>
      <label>Oranges</label>
      <values><value>4</value><value>8</value><value>7</value><value>9</value><value>8</value><value>9</value></values>
    </item>
    <item>
      <label>Watermelon</label>
      <values><value>2</value><value>3</value><value>1</value><value>5</value><value>6</value><value>8</value></values>
    </item>
    <item>
      <label>Peaches</label>
      <values><value>9</value><value>9</value><value>10</value><value>8</value><value>7</value><value>9</value></values>
    </item>
  </records>
</graph>

Reference: gruff's gruff-0.2.9 Documentation [rubyforge.org]
to ruby rmagick image ubuntu gentoo magick graph chart gruff by jrobertson on Feb 24, 2008

C#: Resize An Image While Maintaining Aspect Ratio and Maximum Height

// This allows us to resize the image. It prevents skewed images and
// also vertically long images caused by trying to maintain the aspect
// ratio on images who's height is larger than their width

public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
{
	System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

	// Prevent using images internal thumbnail
	FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
	FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

	if (OnlyResizeIfWider)
	{
		if (FullsizeImage.Width <= NewWidth)
		{
			NewWidth = FullsizeImage.Width;
		}
	}

	int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
	if (NewHeight > MaxHeight)
	{
		// Resize with height instead
		NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
		NewHeight = MaxHeight;
	}

	System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

	// Clear handle to original file so that we can overwrite it if necessary
	FullsizeImage.Dispose();

	// Save resized picture
	NewImage.Save(NewFile);
}

Set image opacity

        public static Image SetOpacity(Image original, float opacity)
        {
            Bitmap temp = new Bitmap(original.Width, original.Height);
            Graphics g = Graphics.FromImage(temp);
            ColorMatrix cm = new ColorMatrix();
            cm.Matrix33 = opacity;

            ImageAttributes ia = new ImageAttributes();
            ia.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            g.DrawImage(original, new Rectangle(0, 0, temp.Width, temp.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, ia);
            g.Dispose();

            return temp;
        } 

Avatar Resizer

I go on a lot of Bulletin Board, every has its own limits of size for the avatars, instead of the resize manually I created a script which does it for me with RMagick

#!/usr/bin/ruby
require "RMagick"
$SIZES = [80 , 100 , 110 , 128]

if !ARGV[0]
  puts "Usage: mk_avatars.rb SourceAvatarPath"
  exit
end

image = Magick::Image.read(ARGV[0]).first
$SIZES.each do |sz|
  puts "Generating Avatar : #{sz}"
  out = image.thumbnail(sz,sz)
  file = "out_#{sz}.#{image.format}"
  out.write(file)
end

thumbnail with gd

Function that makes a thumbnail of a imagen and keeps it's proportion. $the fourth parameter ($fill) makes that, if the image is smaller than the size we want, the function expands it. It shows the image directly to the browser, but can be easily modificed to save the imagen on a directory.

Funcion que hace una miniatura de una imagen manteniendo su proporcion individual. El cuarto parametro ($fill) hace que, si la imagen es mas pequeña del tamaño deseado, la expande. Muestra la imagen directamente en el navegador, pero puede ser facilmente modificada para guardarla en un directorio.

<?php
function thumb($img, $w, $h, $fill = true) {
	if (!extension_loaded('gd') && !extension_loaded('gd2')) {
		trigger_error("No dispones de la libreria GD para generar la imagen.", E_USER_WARNING);
		return false;
	}

	$imgInfo = getimagesize($img);
	switch ($imgInfo[2]) {
		case 1: $im = imagecreatefromgif($img); break;
		case 2: $im = imagecreatefromjpeg($img);  break;
		case 3: $im = imagecreatefrompng($img); break;
		default:  trigger_error('Tipo de imagen no reconocido.', E_USER_WARNING);  break;
	}

	if ($imgInfo[0] <= $w && $imgInfo[1] <= $h && !$fill) {
		$nHeight = $imgInfo[1];
		$nWidth = $imgInfo[0];
	}else{
		if ($w/$imgInfo[0] < $h/$imgInfo[1]) {
			$nWidth = $w;
			$nHeight = $imgInfo[1]*($w/$imgInfo[0]);
		}else{
			$nWidth = $imgInfo[0]*($h/$imgInfo[1]);
			$nHeight = $h;
		}
	}
  
	$nWidth = round($nWidth);
	$nHeight = round($nHeight);

	$newImg = imagecreatetruecolor($nWidth, $nHeight);

	imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);

	header("Content-type: ". $imgInfo['mime']);

	switch ($imgInfo[2]) {
		case 1: imagegif($newImg); break;
		case 2: imagejpeg($newImg);  break;
		case 3: imagepng($newImg); break;
		default:  trigger_error('Imposible mostrar la imagen.', E_USER_WARNING);  break;
	}
  
	imagedestroy($newImg);
}
?>


Usage/Uso:
thumb("image.png", 200, 200);

php image from database using PEAR::DB

This fetches an image from a MySQL database (I know, a database may not be the best place to keep images). The image is sent to the web client as an image/jpeg.

<?php
require_once 'DB.php';

define('DB_SERVER', 'localhost');
define('DB_USER', 'php');
define('DB_PASS', '');
define('DB_DATABASE', 'images');
define('DSN', 'mysql://'.DB_USER.':'.DB_PASS.'@'.DB_SERVER.'/'.DB_DATABASE);

global $db;
$db = DB::connect(DSN);

if (PEAR::isError($db)) {
    die($db->getMessage());
}

if (isset($_GET['id'])) {
  header('Content-Type: image/jpeg');
  $id = $_GET['id'];
  $sql = "select image_data from images where id = ?";
  $result =& $db->query($sql, $id);

  if (PEAR::isError($result)) {
    die($result->getMessage());
  } else {
    if ($result->fetchInto($row)) {
      echo $row[0];
    }
  }

} else {
  echo file_get_contents('broken.png');
}
?>

Extensions to CImg

Extensions to CImg, also for interoperability with Fl_Image


#include "CImg.h"
#include <Fl/Fl_Image.H>

using namespace cimg_library;

/* Generates a w*h*3 CImg<unsigned char> image from the given rgba data and background colour. */
CImg<unsigned char> cimg_from_rgba(unsigned char const* rgba,const unsigned int dimw,const unsigned int dimh, 
		const unsigned char back_r, const unsigned char back_g, const unsigned char back_b) {
	CImg<unsigned char> res(dimw,dimh,1,3);
	unsigned char *pR = res.ptr(0,0,0,0), *pG = res.ptr(0,0,0,1), *pB=res.ptr(0,0,0,2);
	const unsigned char *ptrs = rgba;
	for (unsigned int off=res.width*res.height; off>0; --off) {
		*(pR++) = (unsigned char)((ptrs[0] * ptrs[3] + back_r * (255 - ptrs[3])) >> 8);
		*(pG++) = (unsigned char)((ptrs[1] * ptrs[3] + back_g * (255 - ptrs[3])) >> 8);
		*(pB++) = (unsigned char)((ptrs[2] * ptrs[3] + back_b * (255 - ptrs[3])) >> 8);
		ptrs += 4;
	}
	return res;
}

/* Generates a w*h*3 CImg<unsigned char> image from the given rgb data. */
CImg<unsigned char> cimg_from_rgb(unsigned char const* rgb,const unsigned int dimw,const unsigned int dimh) {
	CImg<unsigned char> res(dimw,dimh,1,3);
	unsigned char *pR = res.ptr(0,0,0,0), *pG = res.ptr(0,0,0,1), *pB=res.ptr(0,0,0,2);
	const unsigned char *ptrs = rgb;
	for (unsigned int off=res.width*res.height; off>0; --off) {
		*(pR++) = (unsigned char)*(ptrs++);
		*(pG++) = (unsigned char)*(ptrs++);
		*(pB++) = (unsigned char)*(ptrs++);
	}
	return res;
}

/* Generates a FLTK RGB Image from the given CImg<unsigned char> image. */
Fl_RGB_Image* image_from_cimg(CImg<unsigned char> const & cimg) {
	const unsigned int wh = cimg.dimx() * cimg.dimy();
	unsigned char *buffer = new unsigned char[3*wh], *nbuffer=buffer;
	const unsigned char 
		*ptr1 = cimg.ptr(0,0,0,0),
		*ptr2 = cimg.dim>1?cimg.ptr(0,0,0,1):ptr1,
		*ptr3 = cimg.dim>2?cimg.ptr(0,0,0,2):ptr1;
	for (unsigned int k=0; k<wh; k++) {
		*(nbuffer++) = (unsigned char)(*(ptr1++));
		*(nbuffer++) = (unsigned char)(*(ptr2++));
		*(nbuffer++) = (unsigned char)(*(ptr3++));
	}
	return new Fl_RGB_Image(buffer, cimg.dimx(), cimg.dimy());
}

/* Returns a resized image to a maximum of the given dimensions, keeping its aspect ratio. */
template<typename T> CImg<T> get_resize_keep_aspect_ratio(CImg<T> const & cimg, const unsigned int w, const unsigned int h) {
	if (cimg.dimx() * h > cimg.dimy() * w) { // cimg.dimx() / cimg.dimy() > w / h
		return cimg.get_resize(w, cimg.dimy() * w / cimg.dimx(), -100, -100, 5);
	} else {
		return cimg.get_resize(cimg.dimx() * h / cimg.dimy(), h, -100, -100, 5);
	}
}

/* Returns a resized image to a maximum of the given dimensions, keeping its aspect ratio,
 * only if the dimensions given are smaller than the original dimensions. */
template<typename T> CImg<T> get_resize_if_smaller_keep_aspect_ratio(CImg<T> const & cimg, const unsigned int w, const unsigned int h) {
	if (w < cimg.dimx() || h < cimg.dimy())
		return get_resize_keep_aspect_ratio(cimg, w, h);
	else
		return CImg<T>(cimg);
}

J2ME - Rescale Image

// description of your code here

private Image rescaleImage(Image image, int width, int height)
	{
		int sourceWidth = image.getWidth();
		int sourceHeight = image.getHeight();
	
		Image newImage = Image.createImage(width, height);
		Graphics g = newImage.getGraphics();
		
		for(int y=0; y<height; y++)
		{
			for(int x=0; x<width; x++)
			{
				g.setClip(x, y, 1, 1);
				int dx = x * sourceWidth / width;
				int dy = y * sourceHeight / height;
				g.drawImage(image, x-dx, y-dy, Graphics.LEFT | Graphics.TOP);
			}
		}
		
		return Image.createImage(newImage);
	}

www.webscriptexpert.com - Java - Image based tool tips

// This script creates 'tool tips' for images. Use as much text as you want. Formatting is controlled through the use of style sheets. The text will resize, according to the screen width and placement of the cursor.



<!-- TWO STEPS TO INSTALL IMAGE TOOL TIPS:

1. Copy the coding into the HEAD of your HTML document
2. Add the last code into the BODY of your HTML document -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document -->

<HEAD>

<style type="text/css">
<!--
#toolTipBox {
display: none;
padding: 5;
font-size: 12px;
border: black solid 1px;
font-family: verdana;
position: absolute;
background-color: #ffd038;
color: 000000;
}
-->
</style>

<script type="text/javascript">
<!--
Created by: Saul Salvatierra :: http://myarea.com.sapo.pt
with help from Ultimater :: http://ultimiacian.tripod.com */

var theObj="";

function toolTip(text,me) {
theObj=me;
theObj.onmousemove=updatePos;
document.getElementById('toolTipBox').innerHTML=text;
document.getElementById('toolTipBox').style.display="block";
window.onscroll=updatePos;
}

function updatePos() {
var ev=arguments[0]?arguments[0]:event;
var x=ev.clientX;
var y=ev.clientY;
diffX=24;
diffY=0;
document.getElementById('toolTipBox').style.top = y-2+diffY+document.body.scrollTop+ "px";
document.getElementById('toolTipBox').style.left = x-2+diffX+document.body.scrollLeft+"px";
theObj.onmouseout=hideMe;
}
function hideMe() {
document.getElementById('toolTipBox').style.display="none";
}
-->
</script>
</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document -->

<BODY>

<div align="center">
<span id="toolTipBox" width="200"></span>
<img src="yourImage.jpg" width="237" height="197" border="0" onmouseover="toolTip('Place your tool tip here',this)">
</div>

<p><center>
<font face="arial, helvetica" size"-2">Free JavaScripts provided<br>
by <a href="http://www.webscriptexpert.com">Web Script Expert </a></font>
</center><p>

Python - Example Simple ImageView

import pygtk; pygtk.require('2.0')
import gtk

class Image_Example(object):

	def pressButton(self, widget, data=None):
		print "Pressed"

	def delete_event(self, widget, event, data=None):
		print "delete event occured"

		return False

	def destroy(self, widget, data=None):
		gtk.main_quit()

	def __init__(self):
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("delete_event", self.delete_event)
		self.window.connect("destroy", self.destroy)
		self.window.set_border_width(10)

		self.button = gtk.Button()
		self.button.connect("clicked", self.pressButton, None)
		self.button.connect_object("clicked", gtk.Widget.destroy, self.window)

		self.image = gtk.Image()
		self.image.set_from_file("/tmp/f27.jpg")
		self.image.show()

		self.button.add(self.image)
		self.window.add(self.button)
		self.button.show()
		self.window.show()

	def main(self):
		gtk.main()


if __name__ == '__main__':

	Image_Example().main()
« Newer Snippets
Older Snippets »
Showing 1-10 of 58 total  RSS