Search code examples
htmlcsspngalpha-transparency

How to make hybrid JPG / PNG with 8-bit alpha


I would like to put a big (almost full screen) alpha transparent image on a website, but I have the following problem:

  • if I use JPG the size and compression is OK, but I cannot make it transparent (100 kB)

  • if I use PNG-24 the size is HUGE (3-4 MB)

  • if I use PNG-24 and http://www.8bitalpha.com/ to convert it to PNG-8 then the size is smaller but I cannot reproduce the original graphics in 256 colors. The size is still quite big (700 kB)

What I was thinking about is what if I create PNG-8 files just for the transparent regions and a JPG image for the non-transparent regions. And use absolute positioning to move things into place. Has anyone done anything like this?

Or an other idea, but that's something I really don't have experience with: is it possible to use a JPG image and combine it with alpha transparency from an 8-bit PNG? I mean using JS or CSS3 or Canvas or something what I have never used before?

Here is the page where I'm using PNG-8 now, but it's quite big (700 kb) and some colors are lost.

http://ilhaamproject.com/sand-texture-2/


Solution

  • I've used the same JPG + PNG trick before with large, transparent background images. Take your large image and cut it up into 2 types of rectangular pieces:

    1. Those that don't need transparency (save as JPG)
    2. Those that do need transparency (save as PNG)

    The goal is to get as much image detail as possible saved as JPG.

    Next you'll need to piece everything back together using relative and absolute positioning:

    <div class="bg">
        <div class="content">
            http://slipsum.com
        </div>
    
        <div class="section top"></div>
        <div class="section middle"></div>
        <div class="section bottom"></div>
    </div>
    
    .bg {
        width: 600px; /* width of your unsliced image */
        min-height: 800px; /* height of your unsliced image, min-height allows content to expand */
        position: relative; /* creates coordinate system */
    }
    
    /* Your site's content - make it appear above the sections */
    .content {
        position: relative;
        z-index: 2;
    }
    
    /* Define the sections and their background images */
    .section {
        position: absolute;
        z-index: 1;
    }
    
    .section.top {
        width: 600px;
        height: 200px;
        top: 0;
        left: 0;
        background: url(top.png) no-repeat 0 0;
    }
    
    .section.middle {
        width: 600px;
        height: 400px;
        top: 200px;
        left: 0;
        background: url(middle.jpg) no-repeat 0 0;
    }
    
    .section.bottom {
        width: 600px;
        height: 200px;
        top: 600px;
        left: 0;
        background: url(bottom.png) no-repeat 0 0;
    }