Saturday, October 11, 2008

Disable Firefox Image Drag

Firefox 3 has a behavior where clicking an image and moving your mouse will start to drag a preview of that image around. The behavior even occurs with the background images for elements.

While this drag and drop behavior for images in Firefox can be really usefull for the visitor, this behavior can be a real problem if you're writing an application that depends on JS to drag around elements that contain images or have background images.

Placing the image or element inside a container and attaching event listeners to that container instead of the image or element with a background seems like an obvious answer, but it will only work for the first click. If the visitor drops the element and tries to drag it again Firefox will start up with the drag and drop behavior.

What does work though is having your mousedown event listener prevent the default action, which seems to be that drag and drop behavior.

Within the event handler you're assigning to your mousedown event, assuming you're argument list includes an event object, as is the case with most jQuery event handlers, your function declaration might look like this.

var callback = function(event){
// Other code...

Nice and easy.

Friday, October 10, 2008

PHP: JPEG/JPG DPI function

While working with a lot of JPEG images lately I needed to be able to set the DPI with PHP and I was having trouble finding a way to do that with the native PHP or GD functions. The stuff I did find seemed to be overly complicated or just plain wrong.

So I wrote my own DPI function for PHP that rather than doing pointless resampling simply adjusts the file header.
My needs didn't require me to do it "right", but it will handle from 1 to 255 DPI.

@$jpg -- Path to a jpg file
@$dpi -- DPI to use (1-255)
function set_dpi($jpg, $dpi = 163)
$fr = fopen($jpg, 'rb');
$fw = fopen("$jpg.temp", 'wb');

stream_set_write_buffer($fw, 0);

fwrite($fw, fread($fr, 13) . chr(1) . chr(0) . chr($dpi) . chr(0) . chr($dpi));

fseek($fr, 18);
stream_copy_to_stream($fr, $fw);


rename("$jpg.temp", $jpg);