kandi background
Explore Kits

ImagePicker | 完全仿微信的图片选择,并且提供了多种图片加载接口,选择图片后可以旋转,可以裁剪成矩形或圆形,可以配置各种其他的参数 | iOS library

 by   jeasonlzy Java Version: 0.5.1 License: Apache-2.0

 by   jeasonlzy Java Version: 0.5.1 License: Apache-2.0

Download this library from

kandi X-RAY | ImagePicker Summary

ImagePicker is a Java library typically used in Mobile, iOS applications. ImagePicker has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has medium support. You can download it from GitHub.
完全仿微信的图片选择,并且提供了多种图片加载接口,选择图片后可以旋转,可以裁剪成矩形或圆形,可以配置各种其他的参数
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • ImagePicker has a medium active ecosystem.
  • It has 4191 star(s) with 1038 fork(s). There are 121 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 159 open issues and 119 have been closed. On average issues are closed in 46 days. There are 13 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of ImagePicker is 0.5.1
ImagePicker Support
Best in #iOS
Average in #iOS
ImagePicker Support
Best in #iOS
Average in #iOS

quality kandi Quality

  • ImagePicker has 0 bugs and 0 code smells.
ImagePicker Quality
Best in #iOS
Average in #iOS
ImagePicker Quality
Best in #iOS
Average in #iOS

securitySecurity

  • ImagePicker has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • ImagePicker code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
ImagePicker Security
Best in #iOS
Average in #iOS
ImagePicker Security
Best in #iOS
Average in #iOS

license License

  • ImagePicker is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
ImagePicker License
Best in #iOS
Average in #iOS
ImagePicker License
Best in #iOS
Average in #iOS

buildReuse

  • ImagePicker releases are available to install and integrate.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • ImagePicker saves you 2028 person hours of effort in developing the same functionality from scratch.
  • It has 4457 lines of code, 294 functions and 84 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
ImagePicker Reuse
Best in #iOS
Average in #iOS
ImagePicker Reuse
Best in #iOS
Average in #iOS
Top functions reviewed by kandi - BETA

kandi has reviewed ImagePicker and discovered the below as its top functions. This is intended to give you an instant insight into ImagePicker implemented functionality, and help decide if they suit your requirements.

  • Handle touch event .
  • Called when the image was loaded .
  • Action called to take a picture .
  • on image item clicked
  • Initializes the views .
  • Exit the animation .
  • Determine if there is a virtual navigation bar .
  • Get a view of a folder
  • Set the visibility of the navigation bar .
  • Gets the degree of the image .

ImagePicker Key Features

完全仿微信的图片选择,并且提供了多种图片加载接口,选择图片后可以旋转,可以裁剪成矩形或圆形,可以配置各种其他的参数

1.用法

copy iconCopydownload iconDownload
	compile 'com.lzy.widget:imagepicker:0.6.1'  //指定版本

3.代码参考

copy iconCopydownload iconDownload
public class PicassoImageLoader implements ImageLoader {

    @Override
    public void displayImage(Activity activity, String path, ImageView imageView, int width, int height) {
        Picasso.with(activity)//
                   .load(Uri.fromFile(new File(path)))//
                .placeholder(R.mipmap.default_image)//
                .error(R.mipmap.default_image)//
                .resize(width, height)//
                .centerInside()//
                .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)//
                .into(imageView);
    }

    @Override
    public void clearMemoryCache() {
        //这里是清除缓存的方法,根据需要自己实现
    }
}

Licenses

copy iconCopydownload iconDownload
 Copyright 2016 jeasonlzy(廖子尧)

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

How to upload react-native image from expo-image-picker to Express.js backend that is using multer

copy iconCopydownload iconDownload
const openImagePickerAsync = async () => {
  let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
  if (permissionResult.granted === false) {
    alert("Permission to access camera roll is required!");
    return;
  }
  let pickerResult = await ImagePicker.launchImageLibraryAsync();
  if (!pickerResult.cancelled) {
    const uploadResult = await FileSystem.uploadAsync('http://localhost:8000/upload/picture/1', pickerResult.uri, {
      httpMethod: 'POST',
      uploadType: FileSystemUploadType.MULTIPART,
      fieldName: 'demo_image'
    });
  }
}

Image picker scanned to null flutter

copy iconCopydownload iconDownload
PickedFile pickedFile = await picker.getImage(source: ImageSource.camera);

if (pickedFile == null) {
  return null;
}

Directory appDirectory = await getApplicationDocumentsDirectory();
File newImage = File(appDirectory.path + 'fileName');
newImage.writeAsBytes(File(pickedFile.path).readAsBytesSync());

setState(() {
  _image = newImage;
  print(newImage.path + ' test');
});

How to compare two values from two different collections from firebase?

copy iconCopydownload iconDownload
_firestore.collection('Uploading Vehicle Details').add({
  'City': uCity,
  'Vehicle': uDropdownvalue,
  'Description' : description,
  'Phone.No#' : phoneNumber,
});
_firestore.collection('Uploading Vehicle Details')
  .where('City', isEqualTo: 'San Francisco')
  .where('Vehicle', isEqualTo: 'Toyota RAV4')
  .get()
  .then(...);
-----------------------
_firestore.collection('Uploading Vehicle Details').add({
  'City': uCity,
  'Vehicle': uDropdownvalue,
  'Description' : description,
  'Phone.No#' : phoneNumber,
});
_firestore.collection('Uploading Vehicle Details')
  .where('City', isEqualTo: 'San Francisco')
  .where('Vehicle', isEqualTo: 'Toyota RAV4')
  .get()
  .then(...);

PHPickerViewController tapping on Search gets error... "Unable to load photos"

copy iconCopydownload iconDownload
class WrappedPhotoPicker: UIViewController {
  var picker: PHPickerViewController?
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    if let picker = picker {
      present(picker, animated: false)
    }
  }
}
struct WrappedPickerView: UIViewControllerRepresentable {
  @Environment(\.presentationMode) var presentationMode
  @Binding var photoPickerResult: PHPickerResult?
  
  let wrappedPicker = WrappedPhotoPicker()
  
  func makeUIViewController(context: Context) -> WrappedPhotoPicker {
    var config = PHPickerConfiguration()
    config.filter = .images
    config.selectionLimit = 1
    
    let picker = PHPickerViewController(configuration: config)
    picker.delegate = context.coordinator
    
    wrappedPicker.picker = picker
    return wrappedPicker
  }
  
  func updateUIViewController(_ uiViewController: WrappedPhotoPicker, context: Context) {}
  
  func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }
  
  class Coordinator: PHPickerViewControllerDelegate {
    let parent: WrappedPickerView
    
    init(_ parent: WrappedPickerView) {
      self.parent = parent
    }
    
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
      parent.presentationMode.wrappedValue.dismiss()
      parent.wrappedPicker.dismiss(animated: false)
      
      parent.photoPickerResult = results.first
    }
  }
}
-----------------------
class WrappedPhotoPicker: UIViewController {
  var picker: PHPickerViewController?
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    if let picker = picker {
      present(picker, animated: false)
    }
  }
}
struct WrappedPickerView: UIViewControllerRepresentable {
  @Environment(\.presentationMode) var presentationMode
  @Binding var photoPickerResult: PHPickerResult?
  
  let wrappedPicker = WrappedPhotoPicker()
  
  func makeUIViewController(context: Context) -> WrappedPhotoPicker {
    var config = PHPickerConfiguration()
    config.filter = .images
    config.selectionLimit = 1
    
    let picker = PHPickerViewController(configuration: config)
    picker.delegate = context.coordinator
    
    wrappedPicker.picker = picker
    return wrappedPicker
  }
  
  func updateUIViewController(_ uiViewController: WrappedPhotoPicker, context: Context) {}
  
  func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }
  
  class Coordinator: PHPickerViewControllerDelegate {
    let parent: WrappedPickerView
    
    init(_ parent: WrappedPickerView) {
      self.parent = parent
    }
    
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
      parent.presentationMode.wrappedValue.dismiss()
      parent.wrappedPicker.dismiss(animated: false)
      
      parent.photoPickerResult = results.first
    }
  }
}
-----------------------
struct WrappedPickerView: UIViewControllerRepresentable {
  @Environment(\.presentationMode) var presentationMode
  @Binding var photoPickerResult: PHPickerResult?
  @Binding var image: UIImage?

  let wrappedPicker = WrappedPhotoPicker()

  func makeUIViewController(context: Context) -> WrappedPhotoPicker {
       var config = PHPickerConfiguration()
       config.filter = .images
       config.selectionLimit = 1

       let picker = PHPickerViewController(configuration: config)
       picker.delegate = context.coordinator

       wrappedPicker.picker = picker
       return wrappedPicker
   }

   func updateUIViewController(_ uiViewController: WrappedPhotoPicker, context: Context) {}

   func makeCoordinator() -> Coordinator {
    Coordinator(self)
   }

  class Coordinator: PHPickerViewControllerDelegate {
      let parent: WrappedPickerView

      init(_ parent: WrappedPickerView) {
          self.parent = parent
      }

     func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        self.parent.presentationMode.wrappedValue.dismiss()
        self.parent.wrappedPicker.dismiss(animated: false)
  
        self.parent.photoPickerResult = results.first
        print(results)
    
        guard let result = results.first else {
        return
       }
    
    
       self.parent.image = nil
    
       DispatchQueue.global().async {
            result.itemProvider.loadObject(ofClass: UIImage.self) { (object, error) in

         guard let imageLoaded = object as? UIImage else {
                return
            }
            DispatchQueue.main.async {
                self.parent.image = imageLoaded
            }    
         }
     }
    
    
   }
  }
 }
-----------------------
.ignoresSafeArea(.keyboard)
-----------------------
.sheet(isPresented: $imagePicker) {
    ImagePicker(store: store)
        .ignoresSafeArea(.keyboard)
}
public struct ImagePicker: UIViewControllerRepresentable {

// Vars and setup stuff...
  @Environment(\.presentationMode) var presentationMode

  let viewStore: ViewStore<ImagePickerState, ImagePickerAction>
  
  public init(store: Store<ImagePickerState, ImagePickerAction>) {
    self.viewStore = ViewStore(store)
  }
  
// UIViewControllerRepresentable required functions
  public func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> some UIViewController {

    // Configuring the PHPickerViewController
    var config = PHPickerConfiguration()
    config.filter = PHPickerFilter.images
    
    let picker = PHPickerViewController(configuration: config)
    picker.delegate = context.coordinator
    return picker
  }
  
  public func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}
  
  public func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }
  
// This is the coordinator that acts as the delegate
  public class Coordinator: PHPickerViewControllerDelegate {
    let parent: ImagePicker
    
    init(_ parent: ImagePicker) {
      self.parent = parent
    }
    
    public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
      picker.dismiss(animated: true)
      
      guard let itemProvider = results.first?.itemProvider,
        itemProvider.canLoadObject(ofClass: UIImage.self) else {
        return
      }
      
      itemProvider.loadObject(ofClass: UIImage.self) { [weak self] image, error in
        if let image = image as? UIImage {
          DispatchQueue.main.async {
            self?.parent.viewStore.send(.imagePicked(image: image))
          }
        }
      }
    }
  }
}
-----------------------
.sheet(isPresented: $imagePicker) {
    ImagePicker(store: store)
        .ignoresSafeArea(.keyboard)
}
public struct ImagePicker: UIViewControllerRepresentable {

// Vars and setup stuff...
  @Environment(\.presentationMode) var presentationMode

  let viewStore: ViewStore<ImagePickerState, ImagePickerAction>
  
  public init(store: Store<ImagePickerState, ImagePickerAction>) {
    self.viewStore = ViewStore(store)
  }
  
// UIViewControllerRepresentable required functions
  public func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> some UIViewController {

    // Configuring the PHPickerViewController
    var config = PHPickerConfiguration()
    config.filter = PHPickerFilter.images
    
    let picker = PHPickerViewController(configuration: config)
    picker.delegate = context.coordinator
    return picker
  }
  
  public func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}
  
  public func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }
  
// This is the coordinator that acts as the delegate
  public class Coordinator: PHPickerViewControllerDelegate {
    let parent: ImagePicker
    
    init(_ parent: ImagePicker) {
      self.parent = parent
    }
    
    public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
      picker.dismiss(animated: true)
      
      guard let itemProvider = results.first?.itemProvider,
        itemProvider.canLoadObject(ofClass: UIImage.self) else {
        return
      }
      
      itemProvider.loadObject(ofClass: UIImage.self) { [weak self] image, error in
        if let image = image as? UIImage {
          DispatchQueue.main.async {
            self?.parent.viewStore.send(.imagePicked(image: image))
          }
        }
      }
    }
  }
}

Passing image from one screen to another - Flutter

copy iconCopydownload iconDownload
  void _openCamera(BuildContext context) async {
    final XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.camera,
    );

    if (pickedFile == null) return;
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (_) => second(image: pickedFile)));
  }
 const second({
    Key? key,
    required this.image,
  }) : super(key: key);

  final XFile image;
 ......

 child: Image.file(File(image.path)),

-----------------------
  void _openCamera(BuildContext context) async {
    final XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.camera,
    );

    if (pickedFile == null) return;
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (_) => second(image: pickedFile)));
  }
 const second({
    Key? key,
    required this.image,
  }) : super(key: key);

  final XFile image;
 ......

 child: Image.file(File(image.path)),

Expo application on iOS crashes when uploading video to Firebase Storage. Works on android, just not iOS

copy iconCopydownload iconDownload

 const videoRef = firebase.storage().ref("video/filename");

  const metadata = { contentType: "video/mp4" };

  const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    xhr.onload = function () {
      resolve(xhr.response);
    };

    xhr.ontimeout = function (e) {
      // XMLHttpRequest timed out. Do something here.

      console.log(e);
    };
    xhr.onerror = function (e) {
      console.log(e);

      reject(new TypeError("Network request failed"));
    };
    xhr.responseType = "blob";
    xhr.open("GET", fileUri, true);
    xhr.timeout = 1000 * 60;
    xhr.send(null);
  });


  var uploadTask = videoRef.put(blob, metadata);

 

  uploadTask.on(
    "state_changed",
    (snapshot) => {
      // Observe state change events such as progress, pause, and resume
      // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
      const progress = snapshot.bytesTransferred / snapshot.totalBytes;

    

      switch (snapshot.state) {
        case firebase.storage.TaskState.PAUSED: // or 'paused'
          console.log("Upload is paused");
          break;
        case firebase.storage.TaskState.RUNNING: // or 'running'
          console.log("Upload is running");
          break;
      }
    },
    (error) => {
      console.log(error);

      // Handle unsuccessful uploads
      blob.close();
    },
    () => {
      // Handle successful uploads on complete
      // For instance, get the download URL: https://firebasestorage.googleapis.com/...
      uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {


console.log("Video file save at:",downloadURL)
       
      });
      blob.close();
    }
  );
-----------------------
const img = await fetch(image_url);
const blob = await img.blob();

Positioning a UIImagePickerController cameraOverlayView on top of the camera preview

copy iconCopydownload iconDownload
imagePicker = CustomPicker()
imagePicker.sourceType = .camera
present(imagePicker, animated: true, completion: nil)


class CustomPicker: UIImagePickerController {
    let overlay = UIView()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let camController = children.first?.children.first?.children.first, overlay.superview == nil {
            overlay.backgroundColor = UIColor(white: 1, alpha: 0.5)
            camController.view.addSubview(overlay)
            overlay.addPinConstraints(top: 0, left: 0, bottom: 0, right: 0)
        }
    }
}

extension UIView {
    func addPinConstraints(top: CGFloat? = nil, left: CGFloat? = nil, bottom: CGFloat? = nil, right: CGFloat? = nil) {
        guard let parent = superview else { return }
        translatesAutoresizingMaskIntoConstraints = false
        if let left = left {
            leadingAnchor.constraint(equalTo: parent.leadingAnchor, constant: left).isActive = true
        }
        if let right = right {
            trailingAnchor.constraint(equalTo: parent.trailingAnchor, constant: -right).isActive = true
        }
        if let top = top {
            topAnchor.constraint(equalTo: parent.topAnchor, constant: top).isActive = true
        }
        if let bottom = bottom {
            bottomAnchor.constraint(equalTo: parent.bottomAnchor, constant: -bottom).isActive = true
        }
    }
}

Flutter receives 422 response from Fastapi when posting a PNG file

copy iconCopydownload iconDownload
  final request = http.MultipartRequest(
    'POST',
    Uri.parse('http://<my locally hosted ip>:8345/api/predict'),
  );

  request.files.add(
    await http.MultipartFile.fromPath(
      'file', // NOTE - this value must match the 'file=' at the start of -F
      image1.path,
      contentType: MediaType('image', 'png'),
    ),
  );

  final response = await http.Response.fromStream(await request.send());

  print(response.body);

type 'Null' is not a subtype of type 'File' of 'function result' in flutter?

copy iconCopydownload iconDownload
File? _image;
-----------------------
File? _image;

final picker=ImagePicker();

Future choiceImage() async{
 var pickedImage= await picker.getImage(source: ImageSource.gallery);
   if(pickedImage!=null)
     {
       setState(() 
          {
           _image=File(pickedImage!.path);
         });
      }
    }

How to show image from gallery in realitykit?

copy iconCopydownload iconDownload
import ARKit
import RealityKit

class ViewController: UIViewController {
    
    @IBOutlet var arView: ARView!
    var anchor: AnchorEntity!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.anchor = AnchorEntity(world: [0,0,-1])
        
        let ball: MeshResource = .generateSphere(radius: 0.25)
        
        var material = UnlitMaterial()
        
        if #available(iOS 15.0, *) {

            material.color = try! .init(tint: .white,
                                     texture: .init(.load(named: "img", 
                                                             in: nil)))
        }
        
        let ballEntity = ModelEntity(mesh: ball, materials: [material])
        
        self.anchor.addChild(ballEntity)
        
        self.arView.scene.anchors.append(self.anchor)
    }
}

Community Discussions

Trending Discussions on ImagePicker
  • How to upload react-native image from expo-image-picker to Express.js backend that is using multer
  • Image picker scanned to null flutter
  • PlatformException(multiple_request, Cancelled by a second request, null, null) in imagePicker
  • How to compare two values from two different collections from firebase?
  • PHPickerViewController tapping on Search gets error... &quot;Unable to load photos&quot;
  • flutter - Image picker - need to convert 'List&lt;XFile&gt;' to 'List&lt;File&gt;?'
  • Passing image from one screen to another - Flutter
  • Expo application on iOS crashes when uploading video to Firebase Storage. Works on android, just not iOS
  • Positioning a UIImagePickerController cameraOverlayView on top of the camera preview
  • Android API 31 FLAG_IMMUTABLE Error using Firebase Auth UI
Trending Discussions on ImagePicker

QUESTION

How to upload react-native image from expo-image-picker to Express.js backend that is using multer

Asked 2022-Apr-11 at 20:51

as title says, I am trying to upload picture using expo-image-picker and express.js backend

Expo code:

const openImagePickerAsync = async () => {
  let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
  if (permissionResult.granted === false) {
    alert("Permission to access camera roll is required!");
    return;
  }
  let pickerResult = await ImagePicker.launchImageLibraryAsync();
  const dataa = Object.values(pickerResult);
  var data = new FormData();
  data.append('image', {
    path: dataa[2], //image uri
    originalname: "profilePic" + userId + ".jpg",
    type: "image/jpg",
    fieldname: "demo_image"
  })
  console.log(data)
  const uploadImage = await axios.post(`http://localhost:8000/api/upload/picture/` + userId, data);
}

Express code

Router:

var multer = require("multer")
var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    console.log(file)
    cb(null, './controllers/assets/profilePic/');
  },
  filename: function(req, file, cb) {
    console.log(file)
    cb(null, file.originalname);
  }
});
var upload = multer({
  storage: storage
}).single("demo_image");
router.route("/upload/picture/:userId").post(upload, UserController.updatePhoto)

updatePhoto function:

static updateGamePhoto = async (req, res) => {
  try {
    const query = await GamMdl.find({
      game_id: req.params.gameId
    })
    console.log(req.file)
    if (query.length > 0) {
      //get file route
      //get route to db
      const queryy = await GamMdl.updateOne({
        game_id: req.params.gameId
      }, {
        picture: req.file.originalname
      })
      console.log(queryy)
      res.send("1")
    } else {
      //vymaz file
      fs.unlinkSync(req.file.path)
      res.send("0")
    }
  } catch (error) {
    console.log(error)
  }
}

The error I am getting is

2022-04-10T18:17:29.165105+00:00 app[web.1]: undefined
2022-04-10T18:17:29.165435+00:00 app[web.1]: TypeError: Cannot read properties of undefined (reading 'originalname')
2022-04-10T18:17:29.165436+00:00 app[web.1]:     at updatePhoto (/app/controllers/userController.js:166:119)
2022-04-10T18:17:29.165436+00:00 app[web.1]:     at runMicrotasks (<anonymous>)
2022-04-10T18:17:29.165439+00:00 app[web.1]:     at processTicksAndRejections (node:internal/process/task_queues:96:5)

Which most likely means, that object is not being passed or is unable to be parsed correctly.

When I test uploading image only with backend using Postman all works well. Postman preset:

postman preset

How to fix this?

ANSWER

Answered 2022-Apr-10 at 19:25

Don't use axios for file upload because you need to read the image from the native filesystem. You can use uploadAsync() from the FileSystem module from Expo. Documentation Here

In your case the function call would be:

const openImagePickerAsync = async () => {
  let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
  if (permissionResult.granted === false) {
    alert("Permission to access camera roll is required!");
    return;
  }
  let pickerResult = await ImagePicker.launchImageLibraryAsync();
  if (!pickerResult.cancelled) {
    const uploadResult = await FileSystem.uploadAsync('http://localhost:8000/upload/picture/1', pickerResult.uri, {
      httpMethod: 'POST',
      uploadType: FileSystemUploadType.MULTIPART,
      fieldName: 'demo_image'
    });
  }
}

By the way, avoid using localhost since the app may run on a device or emulator, and localhost would be the device itself instead of your webserver. Pass the API endpoint via environment variables. More info here. Use something like dotenv to load variables during development.

Source https://stackoverflow.com/questions/71819433

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install ImagePicker

You can download it from GitHub.
You can use ImagePicker like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the ImagePicker component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.