Update of /cvsroot/freevo/freevo/lib/pyimlib2
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11571

Modified Files:
        Imlib2.py imlib2.c setup.py 
Added Files:
        png.c thumbnail.c thumbnail.h 
Removed Files:
        epeg.c epeg.h 
Log Message:
support for freedesktop.org style thumbnailing

--- NEW FILE: thumbnail.h ---
/*
 * ----------------------------------------------------------------------------
 * Imlib2 wrapper for Python
 * ----------------------------------------------------------------------------
 * $Id: thumbnail.h,v 1.1 2005/04/16 19:40:30 dischi Exp $
 *
 * ----------------------------------------------------------------------------
 * Copyright (C) 2004-2005 Jason Tackaberry <[EMAIL PROTECTED]>
 *
 * First Edition: Dirk Meyer <[EMAIL PROTECTED]>
 * Maintainer:    Dirk Meyer <[EMAIL PROTECTED]>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MER-
 * CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * ----------------------------------------------------------------------------
 */

#ifndef EPEG_HH
#define EPEG_HH

#include <Python.h>

PyObject * epeg_thumbnail(PyObject *self, PyObject *args);
PyObject * png_thumbnail(PyObject *self, PyObject *args);
PyObject * fail_thumbnail(PyObject *self, PyObject *args);

#endif

/* end of epeg.h */

--- epeg.h DELETED ---

Index: setup.py
===================================================================
RCS file: /cvsroot/freevo/freevo/lib/pyimlib2/setup.py,v
retrieving revision 1.7
retrieving revision 1.8
diff -C2 -d -r1.7 -r1.8
*** setup.py    11 Apr 2005 18:46:26 -0000      1.7
--- setup.py    16 Apr 2005 19:40:30 -0000      1.8
***************
*** 31,39 ****
  import sys
  
! files = ["imlib2.c", "image.c", "font.c", "rawformats.c", "epeg.c" ]
  
  include_dirs = []
  library_dirs = []
! libraries    = ['rt']
  
  def check_config(name, minver):
--- 31,40 ----
  import sys
  
! files = ["imlib2.c", "image.c", "font.c", "rawformats.c", "thumbnail.c",
!          "png.c" ]
  
  include_dirs = []
  library_dirs = []
! libraries    = ['rt', 'png']
  
  def check_config(name, minver):

Index: Imlib2.py
===================================================================
RCS file: /cvsroot/freevo/freevo/lib/pyimlib2/Imlib2.py,v
retrieving revision 1.20
retrieving revision 1.21
diff -C2 -d -r1.20 -r1.21
*** Imlib2.py   11 Apr 2005 18:46:26 -0000      1.20
--- Imlib2.py   16 Apr 2005 19:40:30 -0000      1.21
***************
*** 27,36 ****
  # 
-----------------------------------------------------------------------------
  
  
! import _Imlib2, types, math, os
  
  # Counter for auto-generated shared memory names.
  _imlib2_shmem_ctr = 0
  
  def utf8(text):
      """
--- 27,57 ----
  # 
-----------------------------------------------------------------------------
  
+ import types
+ import math
+ import os
+ import glob
+ import md5
  
! import _Imlib2
  
  # Counter for auto-generated shared memory names.
  _imlib2_shmem_ctr = 0
  
+ # thumbnail image dir
+ _thumbnail_dir = os.path.join(os.environ['HOME'], '.thumbnails/large/')
+ if not os.path.isdir(_thumbnail_dir):
+     # create the 'large' dir. Set permissions to user only. All files
+     # inside should also be user only, but who cares when the dir is save?
+     # Yes, I know, it's ugly :)
+     os.makedirs(_thumbnail_dir, 0700)
+ 
+ # dir for failed thumbnails
+ _failed_dir = os.path.join(os.environ['HOME'], '.thumbnails/fail/pyimlib2/')
+ if not os.path.isdir(_failed_dir):
+     # create the 'fail' dir. Set permissions to user only. All files
+     # inside should also be user only, but who cares when the dir is save?
+     # Yes, I know, it's ugly :)
+     os.makedirs(_failed_dir, 0700)
+     
  def utf8(text):
      """
***************
*** 128,133 ****
  
          Returns: If type is 'buffer', return a buffer object containing the 
raw
!                  image data. If type is 'raw', return the pointer and len of 
the
!                  raw image data.
          """
          if type == 'raw':
--- 149,154 ----
  
          Returns: If type is 'buffer', return a buffer object containing the 
raw
!                  image data. If type is 'raw', return the pointer and len of
!                  the raw image data.
          """
          if type == 'raw':
***************
*** 734,738 ****
      It's not perfect, but it's better.
      """
-     import glob, os
      for file in  glob.glob("/dev/shm/pyimlib2*"):
          path, file = os.path.split(file)
--- 755,758 ----
***************
*** 740,743 ****
--- 760,801 ----
  
  
+ def thumbnail_create(src):
+     """
+     Create a freedesktop.org thumbnail.
+     """
+     dst = _thumbnail_dir + md5.md5('file://' + src).hexdigest() + '.'
+     if src.lower().endswith('jpg'):
+         try:
+             _Imlib2.epeg_thumbnail(src, dst + 'jpg', (256,256))
+             return dst + 'jpg'
+         except IOError:
+             pass
+     try:
+         _Imlib2.png_thumbnail(src, dst + 'png', (256,256))
+         return dst + 'png'
+     except:
+         # image is broken
+         dst = _failed_dir + md5.md5('file://' + src).hexdigest() + '.png'
+         _Imlib2.fail_thumbnail(src, dst)
+         return dst
+ 
+ 
+ def thumbnail_check(file):
+     """
+     Check if a freedesktop.org thumbnail exists. Return is either the 
filename,
+     False when the thumbnail can't be created or None is no information is
+     available.
+     """
+     dst = _thumbnail_dir + md5.md5('file://' + file).hexdigest() + '.'
+     if os.path.isfile(dst + 'jpg'):
+         return dst + 'jpg'
+     if os.path.isfile(dst + 'png'):
+         return dst + 'png'
+     dst = _failed_dir + md5.md5('file://' + file).hexdigest() + '.png'
+     if os.path.isfile(dst):
+         return False
+     return None
+ 
+     
  def thumbnail(src, dst, size):
      """
***************
*** 745,753 ****
      image is smaller, do not scale the image.
      """
!     if src.endswith('jpg'):
          try:
              _Imlib2.epeg_thumbnail(src, dst, size)
              return open(dst)
!         except Exception, e:
              pass
      image = open(src)
--- 803,811 ----
      image is smaller, do not scale the image.
      """
!     if src.lower().endswith('jpg'):
          try:
              _Imlib2.epeg_thumbnail(src, dst, size)
              return open(dst)
!         except IOError:
              pass
      image = open(src)

--- epeg.c DELETED ---

--- NEW FILE: thumbnail.c ---
/*
 * ----------------------------------------------------------------------------
 * Imlib2 wrapper for Python
 * ----------------------------------------------------------------------------
 * $Id: thumbnail.c,v 1.1 2005/04/16 19:40:30 dischi Exp $
 *
 * ----------------------------------------------------------------------------
 * Copyright (C) 2004-2005 Jason Tackaberry <[EMAIL PROTECTED]>
 *
 * First Edition: Dirk Meyer <[EMAIL PROTECTED]>
 * Maintainer:    Dirk Meyer <[EMAIL PROTECTED]>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MER-
 * CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * ----------------------------------------------------------------------------
 */

#include <Python.h>
#include "config.h"

#define X_DISPLAY_MISSING
#include <Imlib2.h>

#ifdef USE_EPEG
#include "Epeg.h"
#endif

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/* png write function stolen from epsilon (see png.c) */
extern int _png_write (const char *file, DATA32 * ptr,
                       int tw, int th, int sw, int sh, char *imformat,
                       int mtime, char *uri);

PyObject *epeg_thumbnail(PyObject *self, PyObject *args)
{
    int iw, ih, tw, th;
    char *source;
    char *dest;
    
#ifdef USE_EPEG
    Epeg_Image *im;
    Epeg_Thumbnail_Info info;
#endif

#ifdef USE_EPEG
    if (!PyArg_ParseTuple(args, "ss(ii)", &source, &dest, &tw, &th))
        return NULL;

    im = epeg_file_open(source);
    if (im) {
        epeg_size_get(im, &iw, &ih);

        if (iw > tw || ih > th) {
            if (iw / tw > ih / th)
                th = (ih * tw) / iw;
            else
                tw = (iw * th) / ih;
        } else {
            tw = iw;
            th = ih;
        }
    
        epeg_decode_size_set(im, tw, th);
        epeg_quality_set(im, 80);
        epeg_thumbnail_comments_enable(im, 1);
    
        epeg_file_output_set(im, dest);
        if(!epeg_encode (im)) {
            epeg_close(im);
            Py_INCREF(Py_None);
            return Py_None;
        }
        
        epeg_close(im);
        PyErr_SetString(PyExc_IOError, "epeg failed");
    } else
        PyErr_SetString(PyExc_IOError, "epeg failed");
      
#else
    PyErr_SetString(PyExc_IOError, "epeg support missing");
#endif
    return NULL;
}

PyObject *png_thumbnail(PyObject *self, PyObject *args)
{
    int iw, ih, tw, th;
    char *source;
    char *dest;

    int mtime;
    char uri[PATH_MAX];
    char format[32];
    struct stat filestatus;
    Imlib_Image tmp = NULL;
    Imlib_Image src = NULL;

    if (!PyArg_ParseTuple(args, "ss(ii)", &source, &dest, &tw, &th))
        return NULL;

    if (stat (source, &filestatus) != 0) {
        PyErr_SetString(PyExc_ValueError, "pyimlib2: unable to load image");
        return NULL;
    }
      
    mtime = filestatus.st_mtime;
    if ((tmp = imlib_load_image_immediately_without_cache (source))) {
        imlib_context_set_image (tmp);
        snprintf (format, 32, "image/%s", imlib_image_format ());
        iw = imlib_image_get_width ();
        ih = imlib_image_get_height ();
        if (iw > tw || ih > th) {
            if (iw / tw > ih / th)
                th = (ih * tw) / iw;
            else
                tw = (iw * th) / ih;
        } else {
            tw = iw;
            th = ih;
        }
    } else {
        PyErr_SetString(PyExc_ValueError, "pyimlib2: unable to load image");
        return NULL;
    }
    
    imlib_context_set_cliprect (0, 0, tw, th);
            
    if ((src = imlib_create_cropped_scaled_image (0, 0, iw, ih, tw, th))) {
        imlib_free_image_and_decache ();
        imlib_context_set_image (src);
        imlib_image_set_has_alpha (1);
        imlib_image_set_format ("argb");
        snprintf (uri, PATH_MAX, "file://%s", source);
        if (_png_write (dest, imlib_image_get_data (), tw, th, iw, ih,
                        format, mtime, uri)) {
            imlib_free_image_and_decache ();
            Py_INCREF(Py_None);
            return Py_None;
        }
        imlib_free_image_and_decache ();
    }

    PyErr_SetString(PyExc_ValueError, "pyimlib2: unable to save image");
    return NULL;
}


PyObject *fail_thumbnail(PyObject *self, PyObject *args)
{
    Imlib_Image image = NULL;
    char uri[PATH_MAX];
    char *source;
    char *dest;
    char format[32];

    if (!PyArg_ParseTuple(args, "ss", &source, &dest))
        return NULL;

    image = imlib_create_image(1, 1);
    imlib_context_set_image(image);
    imlib_image_set_has_alpha(1);
    imlib_image_clear_color(0, 0, 0, 0);

    snprintf (uri, PATH_MAX, "file://%s", source);
    snprintf (format, 32, "image/%s", imlib_image_format ());
    
    if (_png_write (dest, imlib_image_get_data (), 1, 1, 1, 1, format, 0, uri)) 
{
        imlib_free_image_and_decache ();
        Py_INCREF(Py_None);
        return Py_None;
    }
    imlib_free_image_and_decache ();
    PyErr_SetString(PyExc_ValueError, "pyimlib2: unable to save image");
    return NULL;
}

Index: imlib2.c
===================================================================
RCS file: /cvsroot/freevo/freevo/lib/pyimlib2/imlib2.c,v
retrieving revision 1.13
retrieving revision 1.14
diff -C2 -d -r1.13 -r1.14
*** imlib2.c    11 Apr 2005 18:46:26 -0000      1.13
--- imlib2.c    16 Apr 2005 19:40:30 -0000      1.14
***************
*** 35,39 ****
  #include "rawformats.h"
  #include "font.h"
! #include "epeg.h"
  #include "config.h"
  
--- 35,39 ----
  #include "rawformats.h"
  #include "font.h"
! #include "thumbnail.h"
  #include "config.h"
  
***************
*** 176,179 ****
--- 176,181 ----
      { "open", imlib2_open, METH_VARARGS }, 
      { "epeg_thumbnail", epeg_thumbnail, METH_VARARGS }, 
+     { "png_thumbnail", png_thumbnail, METH_VARARGS }, 
+     { "fail_thumbnail", fail_thumbnail, METH_VARARGS }, 
      { "_shm_unlink", imlib2__shm_unlink, METH_VARARGS }, 
      { NULL }

--- NEW FILE: png.c ---
/* Code taken from epsilon (http://www.enlightenment.org) */
#include <png.h>

#define X_DISPLAY_MISSING
#include <Imlib2.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#ifndef PATH_MAX
#define PATH_MAX 4096
#endif

int _png_write (const char *file, DATA32 * ptr, int tw, int th, int sw,
                int sh, char *imformat, int mtime, char *uri)
{
  FILE *fp = NULL;
  char mtimebuf[32], widthbuf[10], heightbuf[10];
  int i, j, k, has_alpha = 1, ret = 0;

  png_infop info_ptr;
  png_color_8 sig_bit;
  png_structp png_ptr;
  png_text text_ptr[5];
  png_bytep row_ptr, row_data = NULL;

  if ((fp = fopen (file, "wb"))) {
      if (!
          (png_ptr =
           png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)))
        {
          ret = 1;
        }
      if (!(info_ptr = png_create_info_struct (png_ptr)))
        {
          png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
          ret = 1;
        }
      if (setjmp (png_ptr->jmpbuf))
        {
          png_destroy_write_struct (&png_ptr, &info_ptr);
          ret = 1;
        }

      png_init_io (png_ptr, fp);

      /* setup tags here */
      text_ptr[0].key = "Thumb::URI";
      text_ptr[0].text = uri;
      text_ptr[0].compression = PNG_TEXT_COMPRESSION_NONE;

      snprintf (mtimebuf, 32, "%d", mtime);
      text_ptr[1].key = "Thumb::MTime";
      text_ptr[1].text = mtimebuf;
      text_ptr[1].compression = PNG_TEXT_COMPRESSION_NONE;

      snprintf (widthbuf, PATH_MAX, "%d", sw);
      text_ptr[2].key = "Thumb::Image::Width";
      text_ptr[2].text = widthbuf;
      text_ptr[2].compression = PNG_TEXT_COMPRESSION_NONE;

      snprintf (heightbuf, PATH_MAX, "%d", sh);
      text_ptr[3].key = "Thumb::Image::Height";
      text_ptr[3].text = heightbuf;
      text_ptr[3].compression = PNG_TEXT_COMPRESSION_NONE;

      text_ptr[4].key = "Thumb::Mimetype";
      text_ptr[4].text = imformat;
      text_ptr[4].compression = PNG_TEXT_COMPRESSION_NONE;

      png_set_text (png_ptr, info_ptr, text_ptr, 5);

      if (has_alpha) {
          png_set_IHDR (png_ptr, info_ptr, tw, th, 8,
                        PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
                        PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
#ifdef WORDS_BIGENDIAN
          png_set_swap_alpha (png_ptr);
#else
          png_set_bgr (png_ptr);
#endif
      } else {
          png_set_IHDR (png_ptr, info_ptr, tw, th, 8,
                        PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
                        PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
          row_data = (png_bytep) malloc (tw * 3 * sizeof (char));
      }

      sig_bit.red = 8;
      sig_bit.green = 8;
      sig_bit.blue = 8;
      sig_bit.alpha = 8;
      png_set_sBIT (png_ptr, info_ptr, &sig_bit);

      png_set_compression_level (png_ptr, 9);   /* 0?? ### */
      png_write_info (png_ptr, info_ptr);
      png_set_shift (png_ptr, &sig_bit);
      png_set_packing (png_ptr);

      for (i = 0; i < th; i++)
        {
          if (has_alpha)
            row_ptr = (png_bytep) ptr;
          else
            {
              for (j = 0, k = 0; j < tw; k++)
                {
                  row_data[j++] = (ptr[k] >> 16) & 0xff;
                  row_data[j++] = (ptr[k] >> 8) & 0xff;
                  row_data[j++] = (ptr[k]) & 0xff;
                }
              row_ptr = (png_bytep) row_data;
            }
          png_write_row (png_ptr, row_ptr);
          ptr += tw;
        }

      png_write_end (png_ptr, info_ptr);
      png_destroy_write_struct (&png_ptr, &info_ptr);
      png_destroy_info_struct (png_ptr, &info_ptr);

      ret = 1;
  }
  else
      printf ("pyimlib2: Unable to open \"%s\" for writing\n", tmpfile);

  fflush (fp);
  if (fp)
      fclose (fp);
  if (row_data)
      free (row_data);

  return (ret);
}



-------------------------------------------------------
SF email is sponsored by - The IT Product Guide
Read honest & candid reviews on hundreds of IT Products from real users.
Discover which products truly live up to the hype. Start reading now.
http://ads.osdn.com/?ad_id=6595&alloc_id=14396&op=click
_______________________________________________
Freevo-cvslog mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/freevo-cvslog

Reply via email to