首页 > 解决方案 > 如果使用图像干预包通过IOS设备上传时旋转,如何调整图像大小并重新定向?

问题描述

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

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');">

请帮我写代码,我应该把它放在哪里,以解决这个问题

此代码用于预览图像

  <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 是

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");
    });

标签: iphonelaravelimage-uploadingimage-resizinguiimageorientation

解决方案


下面的代码应该可以帮助您入门。您在这里寻找的两个关键是干预定向调整大小方法,它们应该解决您提到的两个问题。方向将根据 EXIF 数据旋转图像,并且调整大小可以将图像大小调整为您需要的任何规格。

导入立面

use Intervention\Image\Facades\Image;

建议

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

s_general 方法调整

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

似乎不需要您的构造函数。我会放弃它。如果您保留它,我会习惯于更具描述性的变量名称。像 $u 这样的短名称通常被认为是不好的做法。

您有一些未使用的导入 , ,Validator可以将其删除以进行清理。HashMessageBag

您的控制器正在做很多大多数人认为不好的事情。例如,用 html 摸索。10 次中有 9.9 次您可能应该将刀片用于这些事情,因为它是其主要目的之一。

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

抱歉,我知道这不是代码审查,我只是认为一些小建议可能会在将来对您有所帮助。


推荐阅读