Speed up writing CSS backgrounds

I often need to write code like:

background: url("/media/img/footer.png") no-repeat;
width: 960px;
height: 147px;

Whenever I do, I have to find the image, then get the dimensions, then copy and paste them in separately. It’s annoying. To help, I put together this small tool, written in Python and using OSX’s pbcopy. You’ll need to tweak it if you are on a different platform.

I put this into a file called css-background in ~/bin, then ran chmod u+x to make it runnable. All the images I ever use are in /media/img, so you may need to change that if you do anything differently. At some point, I may update this to work out the filepath properly, but personally I don’t need it.

Go to the folder with the image in, and run

css-background image_name.png

After running it, the CSS code is in the clipboard ready to paste.

#!/usr/bin/python

import sys, os, argparse, StringIO, struct

def getImageInfo(data):

    # From http://code.google.com/p/bfg-pages/source/browse/trunk/pages/getimageinfo.py
    data = str(data)
    size = len(data)
    height = -1
    width = -1
    content_type = ''

    # handle GIFs
    if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'):
        # Check to see if content_type is correct
        content_type = 'image/gif'
        w, h = struct.unpack("= 24) and data.startswith('\211PNG\r\n\032\n')
          and (data[12:16] == 'IHDR')):
        content_type = 'image/png'
        w, h = struct.unpack(">LL", data[16:24])
        width = int(w)
        height = int(h)

    # Maybe this is for an older PNG version.
    elif (size >= 16) and data.startswith('\211PNG\r\n\032\n'):
        # Check to see if we have the right content type
        content_type = 'image/png'
        w, h = struct.unpack(">LL", data[8:16])
        width = int(w)
        height = int(h)

    # handle JPEGs
    elif (size >= 2) and data.startswith('\377\330'):
        content_type = 'image/jpeg'
        jpeg = StringIO.StringIO(data)
        jpeg.read(2)
        b = jpeg.read(1)
        try:
            while (b and ord(b) != 0xDA):
                while (ord(b) != 0xFF): b = jpeg.read(1)
                while (ord(b) == 0xFF): b = jpeg.read(1)
                if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
                    jpeg.read(3)
                    h, w = struct.unpack(">HH", jpeg.read(4))
                    break
                else:
                    jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
                b = jpeg.read(1)
            width = int(w)
            height = int(h)
        except struct.error:
            pass
        except ValueError:
            pass

    return content_type, width, height

parser = argparse.ArgumentParser(description='Specify an image')
parser.add_argument('image', action="store", help='image to generate code for')
arguments = parser.parse_args()

f = open(arguments.image, 'r')

info = getImageInfo(f.read())

width = str(info[1])
height = str(info[2])

text = 'background: url("/media/img/'+arguments.image+'") no-repeat;\n'
text += 'width: '+width+'px;\n'
text += 'height: '+height+'px;'

outf = os.popen("pbcopy", "w")
outf.write(text)
outf.close()

Simple!

4 thoughts on “Speed up writing CSS backgrounds

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>