What are the steps to add SVG effects to an image or div element?

Embarking on my first venture into using SVG graphics has left me feeling a bit bewildered. Despite extensive research, I have yet to stumble upon the answer to my current quandary.

The objective at hand is to transform an image, assuming that the source image is colored, into the following appearance:

The primary motivation for this effect stems from the need to rectify poor-quality images (both aesthetically and resolution-wise) that clients may upload onto their websites.

In Photoshop, achieving this outcome involves utilizing Gradient Map alongside a transparent grid in Mode Multiply.

While I've been successful in applying a filter for grayscale and "gradient map," integrating the grid/pattern remains a challenge.

Here's the progress of my code thus far:

SVG file titled gradient-map.svg

<svg xmlns="http://www.w3.org/2000/svg">
   <filter id="duotone_filter">
      <feColorMatrix type="matrix" result="grayscale"
         values="1 0 0 0 0
                 1 0 0 0 0
                 1 0 0 0 0
                 0 0 0 1 0" >
      </feColorMatrix>
      <feComponentTransfer color-interpolation-filters="sRGB" result="duotone">
        <feFuncR type="table" tableValues="0.0039525691 0.5764705882"></feFuncR>
        <feFuncG type="table" tableValues="0.0123456790 0.8431372549"></feFuncG>
        <feFuncB type="table" tableValues="0.0123456790 0.9803921569"></feFuncB>
        <feFuncA type="table" tableValues="0 1"></feFuncA>
     </feComponentTransfer>
  </filter>        
</svg>

HTML snippet

<div class="image">
    <img src="link/to/file" />
</div>

CSS styling

.image {
   filter: url('../images/gradient-map.svg#duotone_filter');
}

Also, here's the SVG template for the pattern/fill:

<svg xmlns="http://www.w3.org/2000/svg" x="0" y="0" width="6px" height="6px" viewBox="0 0 6 6">
   <circle cx="3" cy="3" r="2" />
</svg>

Is this the correct approach? How should I proceed in order to achieve the desired effect?

If you could redirect me to any valuable resources, I would be immensely grateful. I seem to be struggling to find up-to-date guides or articles.

Thank you.

Answer №1

Looks like you're making progress in the right direction. I've created a demo for you to check out, which you can find on Codepen. Here's what the output looks like:

If you need some guidance, there's a great question about how to Overlay grid on responsive image. In my example, I chose to overlay and scale a large transparent PNG instead of using a repeating grid section. Feel free to customize the color, size, and other attributes of your grid overlay according to your preferences.

Note that you can't use pseudo-elements like :after or :before directly with img elements. You'll have to wrap them in a container, or you could use an additional element as shown below:

<div class="img-container">
    <img src="..." />
    <div class="grid-overlay"></div>
</div>

However, personally, I prefer using pseudo-elements to avoid repeating

<div class="grid-overlay"></div>
every time I want to add a grid overlay.

img {
  filter: url(#duotone_filter)
}

.img-container {
  display: inline-block;
  overflow: hidden;
  position: relative;
  height: 375px;
}

.img-container::after {
  content: '';
  display: block;
  position: absolute;
  background-image: url('http://www.freeiconspng.com/uploads/grid-png-31.png');
  background-size: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
<div class="img-container"><img src="http://kb4images.com/images/random-image/37670495-random-image.jpg" /></div>

<svg xmlns="http://www.w3.org/2000/svg">
   <filter id="duotone_filter">
      <feColorMatrix type="matrix" result="grayscale"
         values="1 0 0 0 0
                 1 0 0 0 0
                 1 0 0 0 0
                 0 0 0 1 0" >
      </feColorMatrix>
      <feComponentTransfer color-interpolation-filters="sRGB" result="duotone">
        <feFuncR type="table" tableValues="0.0039525691 0.5764705882"></feFuncR>
        <feFuncG type="table" tableValues="0.0123456790 0.8431372549"></feFuncG>
        <feFuncB type="table" tableValues="0.0123456790 0.9803921569"></feFuncB>
        <feFuncA type="table" tableValues="0 1"></feFuncA>
     </feComponentTransfer>
  </filter>        
</svg>

Here's another example that utilizes only SVGs (symbols):

Lastly, check out this final example that includes two SVG filters and works well in Firefox. The crux of this example lies in using an additional filter to create a composite image. While I used an external SVG in this instance, you can also utilize an inline SVG and reference it by ID.

<filter id="overlay">
    <feImage result="sourceTwo" xlink:href="http://www.vectorstash.com/vectors/vectorstash-grid.svg" width="500" height="375" preserveAspectRatio="none" x="0" y="0" />
    <feComposite in="SourceGraphic" in2="sourceTwo" operator="out" x="0" y="0" />
  </filter>

Answer №2

To streamline the process, you can merge the grid overlay with the filter by incorporating inline SVG for the grid using an feImage primitive.

(I also made adjustments to your grayscale matrix because it previously only utilized the red channel as a source, which could lead to odd outcomes when working with photos heavy on blue or green tones.)

.filterclass {
    filter: url(#duotone_filter);
}
<svg xmlns="http://www.w3.org/2000/svg">
   <filter id="duotone_filter" color-interpolation-filters="sRGB" x="0%" y="0%" width="100%" height="100%">
      <feImage width="6" height="6" xlink:href= "data:image/svg+xml;charset=utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20x%3D%220%22%20y%3D%220%22%20width%3D%226px%22%20height%3D%226px%22%20viewBox%3D%220%200%206%206%22%3E%0A%20%20%20%3Crect%20x%3D%220%22%20y%3D%220%22%20width%3D%226%22%20height%3D%226%22%20fill%3D%22none%22%20stroke%3D%22grey%22/%3E%0A%3C/svg%3E"/>
      <feTile result="overlay"/>


      <feColorMatrix in="SourceGraphic" type="matrix" result="grayscale"
         values=".33 .33 .33 0 0
                 .33 .33 .33 0 0
                 .33 .33 .33 0 0
                 0 0 0 1 0" />

      <feComponentTransfer result="duotone">
        <feFuncR type="table" tableValues="0.0039525691 0.5764705882"></feFuncR>
        <feFuncG type="table" tableValues="0.0123456790 0.8431372549"></feFuncG>
        <feFuncB type="table" tableValues="0.0123456790 0.9803921569"></feFuncB>
        <feFuncA type="table" tableValues="0 1"></feFuncA>
     </feComponentTransfer>
    <feBlend mode="multiply" in="overlay"/>
  </filter>        
</svg>

<div >
<img class="filterclass" src="http://kb4images.com/images/random-image/37670495-random-image.jpg" />
</div>

The provided SVG for the inlined data uri is

    <svg xmlns="http://www.w3.org/2000/svg" x="0" y="0" width="6px" height="6px" viewBox="0 0 6 6">
   <rect x="0" y="0" width="6" height="6" fill="none" stroke="grey"/>
</svg>

If you wish to make modifications, I recommend utilizing this svg+xml converter - here's the link: https://codepen.io/yoksel/details/JDqvs

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Top Margin: Supported by Chrome and Safari

After troubleshooting why the margin-top is not working on Safari, but works fine on Chrome, I discovered a discrepancy. Chrome Upon hovering over an item in the image, the cursor changes as expected. This feature operates smoothly in Chrome. https://i. ...

What is the best way to implement this design using CSS or JavaScript?

I would like to enhance the appearance of my school website during these challenging times of the pandemic by adding some CSS or JavaScript elements. However, I am unsure how to go about it. ...

Dynamic CSS view size parameter

Currently, I am studying how to create responsive designs using CSS. I decided to test out some example code provided on the w3schools website (https://www.w3schools.com/css/tryit.asp?filename=tryresponsive_webpage). However, I encountered an issue where ...

Tips for adjusting the vertical position of an image within a bootstrap column by a small amount

Apologies in advance if this question has already been addressed, and I am struggling to adapt it to my specific scenario. My objective is to adjust the positioning of the two images shown in the screenshot example below so that they align with the grey b ...

Retrieve information from the text input field and proceed with the action outcome

Currently, I am in the process of developing a form on an asp.net website. The objective is to have users land on a page named Software, where two variables are checked for empty values upon loading. If the check reveals emptiness, the Software View is ret ...

CSS-Only tooltip that adjusts size dynamically

Having trouble getting a tooltip to work exactly as desired? I need to implement tooltips for the contents of dynamically built HTML tables. It must be done with CSS only, without relying on JavaScript or events for performance reasons. The challenge is ha ...

Carousel issue with sliding on Bootstrap when deployed on various web servers

I am experiencing a strange issue with my website. I have it installed on two different servers, and while the Carousel works perfectly fine on the first server, it does not slide properly on the second server. Here are the links to each version of the we ...

Purge precise LocalStorage data in HTML/JavaScript

How can a specific item in the localStorage be cleared using javascript within an html file? localStorage.setItem("one"); localStorage.setItem("two"); //What is the method to clear only "one" ...

Understanding which page is being rendered through _app.js in React/Next.js is crucial for seamless navigation and

Currently, I am working on rendering my web navigation and footer on my _app.js file. My goal is to dynamically adjust the style of the navigation and footer based on the specific page being accessed. Initially, I considered placing the navigation and foot ...

Creating semantic advertisement content using HTML5 tags

With the abundance of Semantic tags in html5 for sectioning content and their importance for Search Engines, I now have a need to incorporate advertisements into my articles. My query revolves around identifying a tag that can clearly indicate when child ...

Newbie: Troubleshooting Vue Errors - "Vue is not recognized"

I'm currently at the beginning stages of learning Vue and am practicing implementing it. However, I keep encountering the errors "vue was used before it was defined" and "Vue is not defined". Below are excerpts from my HTML and JS files for reference. ...

Tips for resizing the background to match the font size on a canvas marker in Google Maps

Check out my jsFiddle code below: var marker = new google.maps.Marker({ position: new google.maps.LatLng(-25.363882,131.044922), map: map, title:"Hello World!", icon: CanvasCrear("hola", 15) ...

Place a div on top of a table

I am facing a challenge with table rows and divs. The height of the table row is set to 100px, while divs can be up to 200px. I want the div to overlay the table and cover the bottom row if it exceeds the row's height. Currently, I have achieved this ...

jQuery image resizing for elements

I have successfully adjusted the images in the gallery to display one per row for horizontal orientation and two per row for vertical orientation. Now, I am facing a challenge in making the images scalable so they can resize dynamically with the window. A ...

Tips for including subjects in JSON data

I am trying to include the subject in JSON data so that I can fetch it using $.each(data.subject). Below is my API code where I am retrieving all the data encoded in JSON format. Any assistance would be greatly appreciated. [{"id":"79","FirstName":"Elon", ...

Adjust the size and color of text in Chart.js using Angular 5

Why does the font color in chartjs appear as light gray and not print when you want to do so from the page? I tried changing the font color of chartjs in the options attribute, but it didn't work. How can I change the font color in chartjs angular? ...

What is the best way to include default text in my HTML input text field?

Is it possible to include uneditable default text within an HTML input field? https://i.stack.imgur.com/eklro.png Below is the current snippet of my HTML code: <input type="text" class="form-control input-sm" name="guardian_officeno" placeholder="Off ...

The child div can be scrolled horizontally, while the parent window remains fixed

I am facing a challenge with my HTML and CSS setup. I want to create a child div that scrolls horizontally, but I do not want the parent window to scroll along with it. Below is my current code: <div id="parent"> <div id="div1"> . ...

jQuery seems to have difficulty selecting the text of a hyperlink's element using the text() or html() methods

I have a <a href=#>Title</a> link and it's the content in between <a href="#"> attribute that I am trying to target but haven't been successful using either the text() or html() jQuery functions. The text() method is returning ...

When using iOS, the video compressing process stops automatically if the screen is no longer active while the file input

I am working on a web application that includes a file upload feature for large videos, typically 30 minutes or longer in duration. When a user on an iOS device selects a video to upload, the operating system will automatically compress it before triggerin ...