当使用图像干预程序包通过IOS设备上传图像时,如果图像旋转,如何调整图像的大小并重新定向? [英] how to resize image and reorient it if it rotates when uploaded through IOS devices using image intervention package?

查看:66
本文介绍了当使用图像干预程序包通过IOS设备上传图像时,如果图像旋转,如何调整图像的大小并重新定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在stackoverflow上的其他开发人员提供的一些教程视频和代码的帮助下开发了Laravel Web应用程序.该应用程序运行良好,除了图像上传功能.我面临着一个问题,该问题与通过任何IOS设备上载的图像在侧面或底部被剪切以及在图像被旋转时在侧面或底部被剪切有关.我已经安装了图像干预工具,但是我不知道将代码放在文件中的什么位置,我在共享控制器代码以及此处显示图像的代码 控制器代码

I have developed a Laravel web application with the help of some tutorial videos and codes given by other developers on stackoverflow .The app is working pretty good except for the image upload feature. I am facing an issue related to the uploaded image being cut either on the sides or on the bottom as well as the image when uploaded through any IOS device then the image under goes rotation. I have installed image intervention but i don't know where to put the code inside my files i am sharing my controller code as well as the image displaying code here controller code

namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\MessageBag;
use App\comment;
use App\User;
use App\post;
use View;
use Lang;
use image;
class usersController extends Controller
{
    private $u;

    public function __construct(){
        $this->u = new User();
    }
    public function search(Request $request){
        $search_input = $request["input"];
        $path = $request["path"];
        $users = User::where("name","like","%$search_input%")->orWhere("username","like","%$search_input%")->get();

        if ($users->isEmpty()) {
            return "<p style='text-align: center;width: 100%;color: gray;font-size: 12px;margin: 3px'>".Lang::get('trans.nothingToShow')."</p>";
        }else{
            foreach ($users as $user) {
                if ($user->verify == 1) {
                    $ifVerify = '<span class="verify-badge" style="width: 420px; height: 700px; background:  url(\''.$path.'/imgs/verify.png\') no-repeat; background-size: cover; margin: 0px 2px;"></span>';
                }else{
                    $ifVerify = '';
                }
                if($user->avatar == "avatar.png"){
                    $avatar_path = '/imgs/avatar.png';
                }else{
                    $avatar_path = '/storage/avatar/'.$user->avatar;
                }
                echo '<div class="navbar-search-item">
                    <a href="'.$path.'/'.$user->username.'">
                        <div>
                            <div style="background-image:url(\''.$path.$avatar_path.'\');">
                            </div>
                            <p>
                                '.$user->name.$ifVerify.'<br>
                                <span>@'.$user->username.'</span>
                            </p>
                        </div>
                    </a>
                </div>';
            }
        }
    }
    public function profile($username){
        $user_info = User::where("username",$username)->get();
        foreach ($user_info as $uinfo) {
            $user_id = $uinfo->uid;
        }
        if (isset($user_id)) {
            $feedbacks = post::where("to_id",$user_id)->where("privacy",1)->orderBy('time', 'desc')->get();
            $feedbacks_count = post::where("to_id",$user_id)->get()->count();
            $new_count = post::where("to_id",$user_id)->where('read',0)->get()->count();
            // check comments on post (count)
            $commentsCount = array();
            foreach ($feedbacks as $fb) {
                $pid = $fb->pid;
                $countComments = comment::where("c_pid",$pid)->get()->count();
                array_push($commentsCount,$countComments);
            }
            return view("pages.profile")->with(["user_info" => $user_info,"feedbacks" => $feedbacks,'feedbacks_count' => $feedbacks_count,'new_count' => $new_count,'commentsCount' => $commentsCount]);
        }else{
            return view("pages.profile")->with(["user_info" => $user_info]);
        }
    }
    public function settings($username){
        $user_info = User::where("username",$username)->get();
        if (Auth::user()->username == $username) {
            return view("pages.settings")->with("user_info",$user_info);
        }else{
            return redirect()->back();
        }

    }
    public function s_general(Request $request){
        $this->validate($request,[
            'avatar' => 'nullable|image|mimes:jpeg,png,jpg|max:3072',
            'fullname' => 'required',
            'email' => 'required|email'
        ]);
        if ($request['fullname'] == Auth::user()->name && $request['email'] == Auth::user()->email && !$request->hasFile('avatar')) {
            return redirect()->back()->with('general_msg', Lang::get('trans.noChanges_MSG'));
        }else{
            $avatar = $request->file('avatar');
            if ($request->hasFile('avatar')) {
                $avatar_ext = $avatar->getClientOriginalExtension();
                $avatar_name = rand(9,999999999)+time().".".$avatar_ext;
                $avatar_new = $avatar->storeAs("avatar",$avatar_name);
            }else{
                $avatar_name = Auth::user()->avatar;
            }
            $update_general = User::where('uid',Auth::user()->uid)->update(['name' => $request['fullname'],'email' => $request['email'],'avatar' => $avatar_name]);
            return redirect()->back()->with('general_msg', Lang::get('trans.changes_saved'));
        }

    }

这就是我显示图像的方式 <div class="profile-avatar" style="width: 300px;height:400px; border-radius: 0%;background-image: url('@if(Auth::user()->avatar == "avatar.png") {{ url("/imgs/".Auth::user()->avatar) }} @else {{ url("/storage/avatar/".Auth::user()->avatar) }} @endif');">

and this is how i display the image <div class="profile-avatar" style="width: 300px;height:400px; border-radius: 0%;background-image: url('@if(Auth::user()->avatar == "avatar.png") {{ url("/imgs/".Auth::user()->avatar) }} @else {{ url("/storage/avatar/".Auth::user()->avatar) }} @endif');">

请帮助我提供代码以及应该放在哪里,以解决此问题

please help me with code should i put and where i should put that in order to resolve this issue

此代码用于预览图片

  <div style="display: inline-flex;">
    <div class="profile-avatar" id="settings_img_elm" style="margin: 10px; width:350px;margin-top: 0; margin-bottom: 0;border-color: #fff; text-align: center;background-image: url('@if(Auth::user()->avatar == "avatar.png") {{ url("/imgs/".Auth::user()->avatar) }} @else {{ url("/storage/avatar/".Auth::user()->avatar) }} @endif');">
  </div>
  <p style="color: #a7aab5; font-size: 9px;padding: 25px 10px 25px 10px; margin: 0;">@lang("trans.preview")<br>@lang("trans.maxSize")<br>upload vertical <br>images.<br>Save the<br>image first<br> and then<br> check the<br> preview</p>
  </div>
  <p style="border-bottom: 1px solid #dfe2e6;margin: 0; margin-top: 12px; margin-bottom: 12px;">
    <input type="file" name="avatar" style="display: none;" id="settings_img">
    <label for="settings_img" class="btn btn-success">@lang("trans.selectImage")</label>

预览图像的javascript是

the javascript for the preview image is

function imagePreview(input,elm) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $(elm).css("background-image","url('"+e.target.result+"')");
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
    $("#settings_img").on("change",function(){
        imagePreview(this,"#settings_img_elm");
    });
    $("#feedback_hFile").on("change",function(){
        $(".send_feedback_image").show();
        imagePreview(this,"#sfb_image_preview");
    });

推荐答案

下面的代码将帮助您入门.您在此处查找的两个关键内容是干预定位

The code below should get you started. The two key things you are looking for here are Interventions orientate and resize methods which should take care of the two issues you mention. Orientation will rotate the image based on EXIF data, and resize can resize your image to whatever specifications you need.

导入立面

use Intervention\Image\Facades\Image;

建议

从导入中删除use image;,因为它可能会导致或将导致您出现问题.无效.

Remove use image; from your imports as it is probably causing or going to cause you issues. It is invalid.

s_常规方法调整

public function s_general(Request $request){
    $this->validate($request,[
        'avatar' => 'nullable|image|mimes:jpeg,png,jpg|max:3072',
        'fullname' => 'required',
        'email' => 'required|email'
    ]);

    if ($request['fullname'] === Auth::user()->name && $request['email'] === Auth::user()->email && !$request->hasFile('avatar')) {
        return redirect()->back()->with('general_msg', Lang::get('trans.noChanges_MSG'));
    }

    if ($request->hasFile('avatar')) {
        // Grab the original image from the request
        $originalImage = $request->file('avatar');

        // Grab the original image extension
        $originalExtension = $originalImage->getClientOriginalExtension();

        // Instantiate a new Intervention Image using our original image,
        // read the EXIF 'Orientation' data of the image and rotate the image if needed
        $newImage = Image::make($originalImage)->orientate();

        // Resize the new image to a width of 300 and a height of null (auto)
        // we also use a callback to constrain the aspect ratio so we don't distort the image on resize
        $newImage->resize(300, null, function ($constraint) {
            $constraint->aspectRatio();
        });

        // Generate a randomized filename and append the original image extension
        $filename = random_int(9, 999999999) + time() . '.' . $originalExtension;

        // Save the new image to disk
        $newImage->save(storage_path('app/public/avatar/' . $filename));
    } else {
        $filename = Auth::user()->avatar;
    }

    User::where('uid', Auth::user()->uid)->update(
        [
            'name' => $request['fullname'],
            'email' => $request['email'],
            'avatar' => $filename
        ]);

    return redirect()->back()->with('general_msg', Lang::get('trans.changes_saved'));
}

更多建议

我知道这不是代码审查,但是 使用PascalCase作为您的班级名称.我看到您有一些进口,例如App\commentApp\post

I know this isn't a code review, but Use PascalCase for your class names. I see you have a few imports such as App\comment and App\post

似乎不需要您的构造函数.我抛弃它.如果您继续使用它,我将习惯于使用更具描述性的变量名.像$ u这样的短名称通常被认为是不当行为.

Your constructor doesn't seem to be needed. I'd ditch it. If you are keeping it, i would get use to more descriptive variable names. Short names like $u are generally considered bad practice.

您有一些未使用的导入,可以删除ValidatorHashMessageBag进行清理.

You have a few unused imports, Validator, Hash and MessageBag could be removed to clean this up.

您的控制器正在做很多事情,大多数人会认为这是不好的做法.以html为例.十分之九,您可能应该利用刀片来完成这些事情,因为这是刀片的主要目的之一.

Your controller is doing a lot of stuff that most would consider bad practice. Fumbling around with html for example. 9.9 times out of 10 you should probably be leveraging blade for these things as it's one of its main purposes.

坚持一种或另一种命名约定.您正在使用camelCase和snake_case的混合变量.我更喜欢camelCase,但是无论您选择哪种方式,都最好坚持使用它,而不要混在一起.

Stick to one naming convention or another. You are using a mixture of camelCase and snake_case for your variables. I prefer camelCase but whichever you choose it's best to stick with it and not mix them.

对不起,我知道这不是代码审查,我只是想一些建议可以在将来对您有所帮助.

Sorry, i know this isn't suppose to be a code review, i just thought that a few little suggestions might help you in the future.

这篇关于当使用图像干预程序包通过IOS设备上传图像时,如果图像旋转,如何调整图像的大小并重新定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆