Steve
Steve

Reputation: 5166

Trim Image Whitespace Using CSS/Javascript?

Has anyone experimented with removing the white (un-used) part of the image using CSS/JS? I have an image (https://i.sstatic.net/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?

Upvotes: 1

Views: 3657

Answers (1)

Roberto Arosemena
Roberto Arosemena

Reputation: 1140

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)

Upvotes: 3

Related Questions