0

Has anyone experimented with removing the white (un-used) part of the image using CSS/JS? I have an image (https://i.stack.imgur.com/qXAHZ.jpg) that contains actual content surrounded by lots of whitespace that I want to remove using pure CSS if possible (perhaps position:absolute; clip:rect(0px,60px,200px,0px); or background-size:cover; or a combination), but unfortunately the location of the actual content in the image file is not known. The desired results is showing the wallet by itself.

I would much rather avoid a JS solution but if there's something that works and fairly performant, it will be awesome! It's possible to do in PIL (Trim whitespace using PIL), but it would nice to avoid it if we have a frontend solution that works well 80%+ of the times.

image with white space

Update: what's the best way to smartly guess (or at least assume) the background position or clip location in a relative way (percentages)? Is it better to use a combination of background-position, clip, and background-size to get the desired effect?

Community
  • 1
  • 1
Steve
  • 4,946
  • 12
  • 45
  • 62

1 Answers1

3

you can use background position, i made this for you

div {
  background: url('http://i.imgur.com/oA5ezhv.jpg') no-repeat;
  width: 230px;
  height: 160px;
  background-position: -35px -180px;
}

It makes an empty container of the size of the crop and then positions the background based on the position of the subject

Here is the example working

If the image is dynamic and the whitespace proportions change then you will need to either use javascript or do it on the server side (gd or imagemagick in php)

Roberto Arosemena
  • 1,140
  • 1
  • 9
  • 18
  • Good edit about the dynamic size, I was just gonna point that out :) – webketje Aug 29 '14 at 22:29
  • Thank you for the answer, upvoted! What are some ways to use JS for images of unknown whitespace proportion? I'm also wondering if it's possible to use CSS background-position w/ percentages instead of pixels? It would awesome to get a solutions that work well most of the time by relying only on the frontend. – Steve Aug 29 '14 at 22:34
  • yes, percentages are possible too, most units as far as i know, and for the javascript part check this question http://stackoverflow.com/questions/12175991/crop-image-white-space-automatically-using-jquery – Roberto Arosemena Aug 29 '14 at 22:36
  • 1
    As an aside, white space like that should be avoided as it does increase files size (and rendering time on a mobile device). However, I'm assuming it is unavoidable somehow in this case... – Jason Aug 29 '14 at 22:56