How do I remove a watermark from jpg and jpeg images?

Download Files with Axios and Vue

Download Files with Axios and Vue

In this artilce, you'll learn how to download file using Axios and Vue with example

If you need to download image or any file from url or blob in Node.js, React.js etc then you can do it using Axios. We can also use get or post request for download file in Vue.js axios. it will also use with Laravel Vue download file.

As we know **Axios **is a very popular for http request. you can fire get, post, put etc request using Axios in Vue.js, Node.js, react js etc. But if you need same requirement to download file response from api and user to give download using Axios then how you can do that? I will help you to do file downloading using Axios.

You can see bellow peace of code for Axios request example:

axios({
    url: 'http://localhost:8000/api/get-file',
    method: 'GET',
    responseType: 'blob',
}).then((response) => {
     var fileURL = window.URL.createObjectURL(new Blob([response.data]));
     var fileLink = document.createElement('a');
  
     fileLink.href = fileURL;
     fileLink.setAttribute('download', 'file.pdf');
     document.body.appendChild(fileLink);
   
     fileLink.click();
});

You can also see full example with Vue.js here:

Make sure you need to create your local pdf file url or you can give any live url for download.

Let's see bellow code:

Example:

<!DOCTYPE html>
<html>
<head>
    <title>How to Download File using Axios Vue JS? - ItSolutionStuff.com</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js" integrity="sha256-S1J4GVHHDMiirir9qsXWc8ZWw74PHHafpsHp5PXtjTs=" crossorigin="anonymous"></script>
</head>
<body>
  
<div id="app">
   
  <button @click="onClick()">DownLoad</button>
  
</div>
  
<script type="text/javascript">
   
    var app = new Vue({
      el: '#app',
      methods: {
          onClick() {
              axios({
                    url: 'http://localhost:8000/my.pdf',
                    method: 'GET',
                    responseType: 'blob',
                }).then((response) => {
                     var fileURL = window.URL.createObjectURL(new Blob([response.data]));
                     var fileLink = document.createElement('a');
   
                     fileLink.href = fileURL;
                     fileLink.setAttribute('download', 'file.pdf');
                     document.body.appendChild(fileLink);
   
                     fileLink.click();
                });
          }
      }
    })
  
</script>
  
</body>
</html>

I hope it can help you...

A Guide To Compress And Upload Images In Laravel 5.8

A Guide To Compress And Upload Images In Laravel 5.8

If you wanted to compress image in laravel 5 application then you are a right place. I will guide you how to compress image before upload using intervention in laravel 5.8. We can easily image minify or image compression in laravel.

If you wanted to compress image in laravel 5 application then you are a right place. I will guide you how to compress image before upload using intervention in laravel 5.8. We can easily image minify or image compression in laravel.

Using intervention we can easily compress image of png, jpeg, jpg, gif, svg etc.

We will use intervention/image package for **compress **or resize **image **in Laravel 5.8. intervention provide a resize function that will take a three parameters. three parameters are width, height and callback function. callback function is a optional.

So here i write step by step tutorial of compress and upload image in Laravel 5.8. So just follow bellow step to create image **example **for your project.

Step 1: Install Laravel 5.8

In this step, if you haven't Laravel 5.8 application setup then we have to get fresh **laravel 5.8 **application. So run bellow command and get clean fresh Laravel 5.8 application.

composer create-project --prefer-dist laravel/laravel blog

Step 2: Install Intervention Image

In second step we will install intervention/image for resize image. this package through we can generate thumbnail image for our project. so first fire bellow command in your cmd or terminal:

composer require intervention/image

Now we need to add provider path and alias path in config/app.php file so open that file and add bellow code.

<strong>config/app.php</strong>

return [
    ......
    $provides => [
        ......
        ......,
        'Intervention\Image\ImageServiceProvider'
    ],
    $aliases => [
        .....
        .....,
        'Image' => 'Intervention\Image\Facades\Image'
    ]
]

Step 3: Create Routes

In this step we will add routes and controller file so first add bellow route in your routes.php file.

<strong>routes/web.php</strong>

Route::get('resizeImage', '[email protected]');
Route::post('resizeImagePost', '[email protected]')->name('resizeImagePost');

Step 4: Create Controller File

Now require to create new ImageController for image uploading and resizeing image so first run bellow command :

php artisan make:controller ImageController

After this command you can find ImageController.php file in your app/Http/Controllers directory. open ImageController.php file and put bellow code in that file.

app/Http/Controllers/ImageController.php

<?php
  
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\Http\Requests;
use Image;
class ImageController extends Controller
{
  
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function resizeImage()
    {
        return view('resizeImage');
    }
  
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function resizeImagePost(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
  
        $image = $request->file('image');
        $input['imagename'] = time().'.'.$image->getClientOriginalExtension();
     
        $destinationPath = public_path('/thumbnail');
        $img = Image::make($image->getRealPath());
        $img->resize(100, 100, function ($constraint) {
            $constraint->aspectRatio();
        })->save($destinationPath.'/'.$input['imagename']);
   
        $destinationPath = public_path('/images');
        $image->move($destinationPath, $input['imagename']);
   
        $this->postImage->add($input);
   
        return back()
            ->with('success','Image Upload successful')
            ->with('imageName',$input['imagename']);
    }
   
}

Step 5: Blade and Create Upload directory

Ok, in this last step we will create resizeImage.blade.php file for photo upload form and manage error message and also success message. So first create resizeImage.blade.php file and put bellow code:

resources/views/resizeImage.blade.php

@extends('layouts.app')
   
@section('content')
<div class="container">
<h1>Resize Image Uploading Demo</h1>
@if (count($errors) > 0)
    <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
   
@if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
    <button type="button" class="close" data-dismiss="alert">×</button>    
    <strong>{{ $message }}</strong>
</div>
<div class="row">
    <div class="col-md-4">
        <strong>Original Image:</strong>
        <br/>
        <img src="/images/{{ Session::get('imageName') }}" />
    </div>
    <div class="col-md-4">
        <strong>Thumbnail Image:</strong>
        <br/>
        <img src="/thumbnail/{{ Session::get('imageName') }}" />
    </div>
</div>
@endif
   
{!! Form::open(array('route' => 'resizeImagePost','enctype' => 'multipart/form-data')) !!}
    <div class="row">
        <div class="col-md-4">
            <br/>
            {!! Form::text('title', null,array('class' => 'form-control','placeholder'=>'Add Title')) !!}
        </div>
        <div class="col-md-12">
            <br/>
            {!! Form::file('image', array('class' => 'image')) !!}
        </div>
        <div class="col-md-12">
            <br/>
            <button type="submit" class="btn btn-success">Upload Image</button>
        </div>
    </div>
{!! Form::close() !!}
</div>
@endsection

Ok, at last create two directory in your public folder (1)images and (2)thumbnail and please give permission to that folder and check....

I hope it can help you...

Convert SVG to PNG Using NodeJS & Sharp

Convert SVG to PNG Using NodeJS & Sharp

In this article, you'll learn how to convert SVG to PNG using NodeJS & Sharp

Introduction

Do you need to convert a SVG file to the Portable Network Graphic (PNG) format? This article will walk you through how to do that.

We'll use Node.js as our coding language of choice and the Sharp npm package to do most of the heavy lifting for us.

Install Sharp Npm Package

First, you need to install the npm package. You can install it with either the npm or yarn command below:

Npm

$ npm install sharp --save

Yarn

$ yarn add sharp

If everything went as planned, you should now have the Sharp npm package installed.

Convert SVG to PNG

Now we're ready to start writing some code and converting an image! Make sure you have a SVG file in the root of your project directory that we can play around with.

Using the Sharp npm package, here is the full code:

Node.js
 
const sharp = require("sharp")
 
sharp("file.svg")
  .png()
  .toFile("new-file.png")
  .then(function(info) {
    console.log(info)
  })
  .catch(function(err) {
    console.log(err)
  })

Let's break down each part of the code:

  1. First, we import the sharp npm package and hold it in the sharp variable.
  2. Then, we use the sharp package to read our file.svg file, convert it to a PNG and write the new PNG file to your directory with the .toFile() function.
  3. The sharp method is a promise and we use it to get the info for the file once it has been written to our directory.
  4. Last, we use .catch() method to catch and console.log() any errors.

When you run the code, you should get a similar output to this:

Output
 
{
  format: 'png',
  width: 2500,
  height: 527,
  channels: 4,
  premultiplied: false,
  size: 47194
}

You should also see the new PNG file in your project directory.

There are also additional options you can pass to the .png() method to alter the output image. These include the compression level, quality, colors, and more. You can check them out in their documentation.

Conclusion

Hopefully, this article helped you in your coding endeavors!

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Best 50 Nodejs interview questions from Beginners to Advanced in 2019

Node.js 12: The future of server-side JavaScript

An Introduction to Node.js Design Patterns

How to use and install Ckeditor with image upload in Laravel 5.8

How to use and install Ckeditor with image upload in Laravel 5.8

In this tutorial, I would like to share with you how to use and install ckeditor with image upload in laravel 5.8. I will use simple laravel image or file upload code with ckeditor file upload in laravel 5.

We will use filebrowseruploadurl and filebrowserUploadMethod function of Ckeditor in Laravel 5. So if you have Ckeditor image upload** **not working in Laravel then i will hep you to how to upload image using Ckeditor in Laravel.

I write very simple example of image uploading with Laravel step by step so you can easily use in your Laravel. Ckeditor is a most powerful tool for content editor. so if you have image upload option also available then it awesome.

So, let's see bellow steps to getting done with image upload in Ckeditor Laravel.

Step 1: Add Routes

First we need to create two routes for display Ckeditor form page and another for image uploading. so let's create it.

routes/web.php

Route::get('ckeditor', '[email protected]');
Route::post('ckeditor/upload', '[email protected]')->name('ckeditor.upload');

Step 2: Create Controller

In this step, we will create new controller as CkeditorController with two method index() and upload(). in index method we will return and view and upload method we will write code of image uploading.

app/Http/Controllers/CkeditorController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class CkeditorController extends Controller
{
    /**
     * success response method.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('ckeditor');
    }
  
    /**
     * success response method.
     *
     * @return \Illuminate\Http\Response
     */
    public function upload(Request $request)
    {
        if($request->hasFile('upload')) {
            $originName = $request->file('upload')->getClientOriginalName();
            $fileName = pathinfo($originName, PATHINFO_FILENAME);
            $extension = $request->file('upload')->getClientOriginalExtension();
            $fileName = $fileName.'_'.time().'.'.$extension;
        
            $request->file('upload')->move(public_path('images'), $fileName);
   
            $CKEditorFuncNum = $request->input('CKEditorFuncNum');
            $url = asset('images/'.$fileName); 
            $msg = 'Image uploaded successfully'; 
            $response = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";
               
            @header('Content-type: text/html; charset=utf-8'); 
            echo $response;
        }
    }
}

Step 3: Create Blade File

Here, we need to create ckeditor.blade.php file and write form logic and ckeditor js code. So let's create it.

resources/views/ckeditor.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 5 Ckeditor Image Upload Example - ItSolutionStuff.com</title>
    <script src="https://cdn.ckeditor.com/4.12.1/standard/ckeditor.js"></script>
</head>
<body>
  
<h1>Laravel 5 Ckeditor Image Upload Example - ItSolutionStuff.com</h1>
<textarea name="editor1"></textarea>
   
<script type="text/javascript">
    CKEDITOR.replace('editor1', {
        filebrowserUploadUrl: "{{route('ckeditor.upload', ['_token' => csrf_token() ])}}",
        filebrowserUploadMethod: 'form'
    });
</script>
   
</body>
</html>

Step 4: Create images folder

In last step, we need to create "images" folder on your public directory. so must be create with permission.

Now we are ready to run our application example with Laravel 5.8 so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/ckeditor

I hope it can help you....

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Learn More about

PHP with Laravel for beginners - Become a Master in Laravel

Projects in Laravel: Learn Laravel Building 10 Projects

Laravel for RESTful: Build Your RESTful API with Laravel

Fullstack Web Development With Laravel and Vue.js

Laravel 5.8 Ajax CRUD tutorial using Datatable JS

Laravel 5.8 Tutorial from Scratch for Beginners

Build RESTful API In Laravel 5.8 Example

Login with Google in Laravel 5.8 App using Socialite Package

Laravel PHP Framework Tutorial - Full Course for Beginners (2019)

Image Panorama Stitching with OpenCV and Python

Image Panorama Stitching with OpenCV and Python

In this article, we will learn how to perform image stitching using Python and OpenCV

Image stitching is one of the most successful applications in Computer Vision. Nowadays, it is hard to find a cell phone or an image processing API that do not contain this functionality.

In this piece, we will talk about how to perform image stitching using Python and OpenCV. Given a pair of images thata share some common region, our goal is to “stitch” them and create a panoramic image scene.

Throughout this article, we go over some of the most famous Computer Vision techniques. These include:

  • Keypoint detection
  • Local invariant descriptors (SIFT, SURF, etc)
  • Feature matching
  • Homography estimation using RANSAC
  • Perspective warping

We explore many feature extractors like SIFT, SURF, BRISK, and ORB. You can follow along using this Colab notebook and even try it out with your pictures.

Feature Detection and Extraction

Given a pair of images like the ones above, we want to stitch them to create a panoramic scene. It is important to note that both images need to share some common region.

Moreover, our solution has to be robust even if the pictures have differences in one or more of the following aspects:

  • Scaling
  • Angle
  • Spacial position
  • Capturing devices

The first step in that direction is to extract some key points and features of interest. These features, however, need to have some special properties.

Let’s first consider a simple solution.

Keypoints Detection

An initial and probably naive approach would be to extract key points using an algorithm such as Harris Corners. Then, we could try to match the corresponding key points based on some measure of similarity like Euclidean distance. As we know, corners have one nice property: they are invariant to rotation. It means that, once we detect a corner, if we rotate an image, that corner will still be there.

However, what if we rotate then scale an image? In this situation, we would have a hard time because corners are not invariant to scale. That is to say, if we zoom-in to an image, the previously detected corner might become a line!

In summary, we need features that are invariant to rotation and scaling. That is where more robust methods like SIFT, SURF, and ORB come in.

Keypoints and Descriptors.

Methods like SIFT and SURF try to address the limitations of corner detection algorithms. Usually, corner detector algorithms use a fixed size kernel to detect regions of interest (corners) on images. It is easy to see that when we scale an image, this kernel might become too small or too big.

To address this limitation, methods like SIFT uses Difference of Gaussians (DoD). The idea is to apply DoD on differently scaled versions of the same image. It also uses the neighboring pixel information to find and refine key points and corresponding descriptors.

To start, we need to load 2 images, a query image, and a training image. Initially, we begin by extracting key points and descriptors from both. We can do it in one step by using the OpenCV detectAndCompute() function. Note that in order to use detectAndCompute() we need an instance of a keypoint detector and descriptor object. It can be ORB, SIFT or SURF, etc. Also, before feeding the images to detectAndCompute() we convert them to grayscale.

def detectAndDescribe(image, method=None):
    """
    Compute key points and feature descriptors using an specific method
    """
    
    assert method is not None, "You need to define a feature detection method. Values are: 'sift', 'surf'"
    
    # detect and extract features from the image
    if method == 'sift':
        descriptor = cv2.xfeatures2d.SIFT_create()
    elif method == 'surf':
        descriptor = cv2.xfeatures2d.SURF_create()
    elif method == 'brisk':
        descriptor = cv2.BRISK_create()
    elif method == 'orb':
        descriptor = cv2.ORB_create()
        
    # get keypoints and descriptors
    (kps, features) = descriptor.detectAndCompute(image, None)
    
    return (kps, features)

We run detectAndCompute() on both, the query and the train image. At this point, we have a set of key points and descriptors for both images. If we use SIFT as the feature extractor, it returns a 128-dimensional feature vector for each key point. If SURF is chosen, we get a 64-dimensional feature vector. The following images show some of the features extracted using SIFT, SURF, BRISK, and ORB.

Detection of key points and descriptors using SIFT

Detection of key points and descriptors using SURF

Detection of key points and descriptors using BRISK and Hamming distances.

Detection of key points and descriptors using ORB and Hamming distances.

Feature Matching

As we can see, we have a large number of features from both images. Now, we would like to compare the 2 sets of features and stick with the pairs that show more similarity.

With OpenCV, feature matching requires a Matcher object. Here, we explore two flavors:

  • Brute Force Matcher
  • KNN (k-Nearest Neighbors)

The BruteForce (BF) Matcher does exactly what its name suggests. Given 2 sets of features (from image A and image B), each feature from set A is compared against all features from set B. By default, BF Matcher computes the Euclidean distance between two points. Thus, for every feature in set A, it returns the closest feature from set B. For SIFT and SURF OpenCV recommends using Euclidean distance. For other feature extractors like ORB and BRISK, Hamming distance is suggested.

To create a BruteForce Matcher using OpenCV we only need to specify 2 parameters. The first is the distance metric. The second is the crossCheck boolean parameter.

def createMatcher(method,crossCheck):
    "Create and return a Matcher Object"
    
    if method == 'sift' or method == 'surf':
        bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=crossCheck)
    elif method == 'orb' or method == 'brisk':
        bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=crossCheck)
    return bf

The crossCheck bool parameter indicates whether the two features have to match each other to be considered valid. In other words, for a pair of features (f1, f2) to considered valid, f1 needs to match f2 and f2 has to match f1 as the closest match as well. This procedure ensures a more robust set of matching features and is described in the original SIFT paper.

However, for cases where we want to consider more than one candidate match, we can use a KNN based matching procedure.

Instead of returning the single best match for a given feature, KNN returns the k best matches.
Note that the value of k has to be pre-defined by the user. As we expect, KNN provides a larger set of candidate features. However, we need to ensure that all these matching pairs are robust before going further.

Ratio Testing

To make sure the features returned by KNN are well comparable, the authors of the SIFT paper, suggests a technique called ratio test. Basically, we iterate over each of the pairs returned by KNN and perform a distance test. For each pair of features (f1, f2), if the distance between f1 and f2 is within a certain ratio, we keep it, otherwise, we throw it away. Also, the ratio value must be chosen manually.

In essence, ratio testing does the same job as the cross-checking option from the BruteForce Matcher. Both, ensure a pair of detected features are indeed close enough to be considered similar. The 2 figures below show the results of BF and KNN Matcher on SIFT features. We chose to display only 100 matching points to clear visualization.

Feature matching using KNN and Ration Testing on SIFT features

Feature matching using Brute Force Matcher on SIFT features

Note that even after cross-checking for Brute force and ratio testing in KNN, some of the features do not match properly.

Nevertheless, the Matcher algorithm will give us the best (more similar) set of features from both images. Now, we need to take these points and find the transformation matrix that will stitch the 2 images together based on their matching points.

Such a transformation is called the Homography matrix. Briefly, the homography is a 3x3 matrix that can be used in many applications such as camera pose estimation, perspective correction, and image stitching. The Homography is a 2D transformation. It maps points from one plane (image) to another. Let’s see how we get it.

Estimating the Homography

RANdom SAmple Consensus or RANSAC is an iterative algorithm to fit linear models. Different from other linear regressors, RANSAC is designed to be robust to outliers.

Models like Linear Regression uses least-squares estimation to fit the best model to the data. However, ordinary least squares is very sensitive to outliers. As a result, it might fail if the number of outliers is significant.

RANSAC solves this problem by estimating parameters only using a subset of inliers in the data. The figure below shows a comparison between Linear Regression and RANSAC. First, note that the dataset contains a fairly high number of outliers.

We can see that the Linear Regression model gets easily influenced by the outliers. That is because it is trying to reduce the average error. Thus, it tends to favor models that minimize the overall distance from all data points to the model itself. And that includes outliers.

On the contrary, RANSAC only fits the model on the subset of points identified as the inliers.

This characteristic is very important to our use case. Here, we are going to use RANSAC to estimate the Homography matrix. It turns out that the Homography is very sensitive to the quality of data we pass to it. Hence, it is important to have an algorithm (RANSAC) that can filter points that clearly belong to the data distribution from the ones which do not.

Comparison between Least Squares and RANSAC model fitting. Note the substantial number of outliers in the data.

Once we have the estimated Homography, we need to warp one of the images to a common plane.

Here, we are going to apply a perspective transformation to one of the images. Basically, a perspective transform may combine one or more operations like rotation, scale, translation, or shear. The idea is to transform one of the images so that both images merge as one. To do this, we can use the OpenCV warpPerspective() function. It takes an image and the homography as input. Then, it warps the source image to the destination based on the homography.

# Apply panorama correction
width = trainImg.shape[1] + queryImg.shape[1]
height = trainImg.shape[0] + queryImg.shape[0]

result = cv2.warpPerspective(trainImg, H, (width, height))
result[0:queryImg.shape[0], 0:queryImg.shape[1]] = queryImg

plt.figure(figsize=(20,10))
plt.imshow(result)

plt.axis('off')
plt.show()

The resulting panorama image is shown below. As we see, there are a couple of artifacts in the result. More specifically, we can see some problems related to lighting conditions and edge effects at the image boundaries. Ideally, we can perform post-processing techniques to normalize the intensities like histogram matching. This would likely make the result look more realistic.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Python

Complete Python Bootcamp: Go from zero to hero in Python 3

Machine Learning A-Z™: Hands-On Python & R In Data Science

Python Tutorial - Python GUI Programming - Python GUI Examples (Tkinter Tutorial)

Python Programming Tutorial | Full Python Course for Beginners 2019

Computer Vision Using OpenCV

OpenCV Python Tutorial - Computer Vision With OpenCV In Python

Python Tutorial: Image processing with Python (Using OpenCV)

A guide to Face Detection in Python

Machine Learning Tutorial - Image Processing using Python, OpenCV, Keras and TensorFlow

Face Detection using Open-CV

A guide to Object Detection with OpenCV and Swift

Input image pair

Panoramic Image

Input image pair

Panoramic Image

Input image pair

Panoramic Image

Input image pair.

Panoramic Image