Friday, April 29, 2011

Protect image from being copied

Hello Friends,

Many times I am asked to protect some copyrighted images over web,
so finally I have found a better way to protect from being copied.
There are some cases by which we can copy the image
Here I have taken care of following cases
  • Right click on image and Save the Image
  • Save the Entire page and all images displayed on page will be downloaded to its Data Folder
  • in mozila Firefox, We can save the media files by following steps
    1. Right click on Page, select “View Page Info”
    2. ViewSourceSandeep
    3. It will open a window, Select “Media” tab, here a list of all files will be available
    4. select particular file and click on “Save As” button to save the media
    5. SavemediaSandeep


Now Let’s Start our main topic,that is protect image from being copied
There is a concept called Data URI scheme.
Generally to display any image on page, we use Relative_URL and if we display image using this, the images can be easily copied.
Here we will save image in database and retrieve the same
To Create table
CREATE TABLE [dbo].[Images](
 [ImageID] [int] IDENTITY(1,1) NOT NULL,
 [ImageName] [varchar](50) NULL,
 [Image] [image] NULL,
 [ext] [varchar](50) NULL,
 CONSTRAINT [PK_Images] PRIMARY KEY CLUSTERED 
(
 [ImageID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Now,

the aspx page will be very simple like





<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <table>
        <tr>
            <td>
                Name
            </td>
            <td>
                <asp:TextBox ID="txtName" runat="server" ValidationGroup="Uploadgrp"></asp:TextBox>
            </td>
            <td>
                <asp:RequiredFieldValidator ID="rfvdName" runat="server" ControlToValidate="txtName"
                    ValidationGroup="Uploadgrp" ErrorMessage="*"></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td>
                Image
            </td>
            <td>
                <asp:FileUpload ID="flImgUpload" runat="server" />
            </td>
            <td>
                &nbsp;
            </td>
        </tr>        
        <tr>
            <td>
            </td>
            <td>
                <asp:Button ID="btnUpload" ValidationGroup="Uploadgrp" runat="server" OnClick="btnUpload_Click"
                    Text="Upload " />
            </td>
            <td>
                &nbsp;
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <asp:Label ID="lblMessage" runat="server"></asp:Label>
            </td>
            <td>
                &nbsp;
            </td>
        </tr>
    </table>
    <table>
        <tr>
            <td>
                <asp:Button ID="btnFetch" runat="server" OnClick="btnFetch_Click" Text="Fetch the Last image" />
            </td>
        </tr>
        <tr>
            <td>
                <img oncontextmenu="return false;" runat="server" id="imgDisplay" style="width: 400px; height: 400px;" />
            </td>
        </tr>
    </table>
</asp:Content>


here  oncontextmenu="return false;" using this line of code you can prevent right click on image.

This will protect image to save by right click


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace TestRequest
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void btnFetch_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["TestBlogConnectionString1"].ConnectionString;
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "Select top 1 ImageName,Image,ext From Images order by imageid desc ";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            SqlDataReader rd = cmd.ExecuteReader();
            rd.Read();
            imgDisplay.Src = GetBase64Image((byte[])rd["Image"], (string)rd["ext"]);
            con.Close();
        }
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string strImageName = txtName.Text.ToString();
            if (flImgUpload.PostedFile != null && flImgUpload.PostedFile.FileName != "")
            {
                byte[] imageSize = new byte[flImgUpload.PostedFile.ContentLength];
                HttpPostedFile uploadedImage = flImgUpload.PostedFile;
                string strext = flImgUpload.FileName.Substring(flImgUpload.FileName.LastIndexOf(".") + 1).ToLower();
                uploadedImage.InputStream.Read(imageSize, 0, (int)flImgUpload.PostedFile.ContentLength);

                SqlConnection con = new SqlConnection();
                con.ConnectionString = ConfigurationManager.ConnectionStrings["TestBlogConnectionString1"].ConnectionString;

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "INSERT INTO Images(ImageName,Image,Ext)  VALUES (@ImageName,@Image,@ext)";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;

                SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);
                ImageName.Value = strImageName.ToString();
                cmd.Parameters.Add(ImageName);

                SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, imageSize.Length);
                UploadedImage.Value = imageSize;
                cmd.Parameters.Add(UploadedImage);

                SqlParameter Ext = new SqlParameter("@Ext", SqlDbType.VarChar, 50);
                Ext.Value = strext;
                cmd.Parameters.Add(Ext);

                con.Open();
                int result = cmd.ExecuteNonQuery();
                con.Close();
                if (result > 0)
                    lblMessage.Text = "File Uploaded";
                txtName.Text = string.Empty;
            }
        }

      
        private string GetBase64Image(byte[] data, string ext)
        {
            string binaryRepresenatation = string.Concat("data:image/" + ext + ";base64,", Convert.ToBase64String(data));
            return binaryRepresenatation;
        }
    }
}

the main game is


 private string GetBase64Image(byte[] data, string ext)
        {
            string binaryRepresenatation = string.Concat("data:image/" + ext + ";base64,", Convert.ToBase64String(data));
            return binaryRepresenatation;
        }

it will generate base64 format of byte[] of Image. and using Data URI scheme it generates image by CSS…


this is very common to implement and will help to protect image

click here to download the source
All the best

No comments: