kandi background
Explore Kits

TakePhoto | 一款用于在Android设备上获取照片(拍照或从相册、文件中选择)、裁剪图片、压缩图片的开源工具库 | Computer Vision library

 by   crazycodeboy Java Version: v4.1.0 License: Apache-2.0

 by   crazycodeboy Java Version: v4.1.0 License: Apache-2.0

Download this library from

kandi X-RAY | TakePhoto Summary

TakePhoto is a Java library typically used in Artificial Intelligence, Computer Vision applications. TakePhoto 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.
3.重写onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults),添加如下代码。.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • TakePhoto has a medium active ecosystem.
  • It has 7150 star(s) with 1497 fork(s). There are 183 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 417 open issues and 140 have been closed. On average issues are closed in 52 days. There are 4 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of TakePhoto is v4.1.0
TakePhoto Support
Best in #Computer Vision
Average in #Computer Vision
TakePhoto Support
Best in #Computer Vision
Average in #Computer Vision

quality kandi Quality

  • TakePhoto has 0 bugs and 0 code smells.
TakePhoto Quality
Best in #Computer Vision
Average in #Computer Vision
TakePhoto Quality
Best in #Computer Vision
Average in #Computer Vision

securitySecurity

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

license License

  • TakePhoto 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.
TakePhoto License
Best in #Computer Vision
Average in #Computer Vision
TakePhoto License
Best in #Computer Vision
Average in #Computer Vision

buildReuse

  • TakePhoto 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.
TakePhoto Reuse
Best in #Computer Vision
Average in #Computer Vision
TakePhoto Reuse
Best in #Computer Vision
Average in #Computer Vision
Top functions reviewed by kandi - BETA

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

  • compress image by quality
  • Take a result .
  • Checks the permission of a given method .
  • Write a bitmap to a file
  • Compress one image
  • Crops an image .
  • Configures the compression configuration
  • Get bitmap degree .
  • Get the intent to capture the location of an image
  • get file with uri

TakePhoto Key Features

继承TakePhotoActivity、TakePhotoFragmentActivity、TakePhotoFragment三者之一。

通过getTakePhoto()获取TakePhoto实例进行相关操作。

重写以下方法获取结果

安装说明

copy iconCopydownload iconDownload
    compile 'com.jph.takephoto:takephoto_library:4.1.0'

使用TakePhoto有以下两种方式:

copy iconCopydownload iconDownload
 void takeSuccess(TResult result);
 void takeFail(TResult result,String msg);
 void takeCancel();

自定义相册

copy iconCopydownload iconDownload
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:theme="@style/CustomToolbarTheme"
    android:background="#ffa352">
</android.support.v7.widget.Toolbar>

自定义裁切工具

copy iconCopydownload iconDownload
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.soundcloud.android.crop.CropImageView
        android:id="@+id/crop_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:background="@drawable/crop__texture"
        android:layout_above="@+id/done_cancel_bar" />
    <include
        android:id="@+id/done_cancel_bar"
        android:layout_alignParentBottom="true"
        layout="@layout/crop__layout_done_cancel"
        android:layout_height="50dp"
        android:layout_width="match_parent" />
</RelativeLayout>

获取图片

copy iconCopydownload iconDownload
/**
 * 从文件中获取图片(不裁剪)
 */
void onPickFromDocuments();
/**
 * 从相册中获取图片(不裁剪)
 */
void onPickFromGallery();
/**
 * 从相机获取图片(不裁剪)
 * @param outPutUri 图片保存的路径
 */
void onPickFromCapture(Uri outPutUri);
/**
 * 图片多选
 * @param limit 最多选择图片张数的限制
 **/
void onPickMultiple(int limit);

裁剪图片

copy iconCopydownload iconDownload
/**
 * 从相机获取图片并裁剪
 * @param outPutUri 图片裁剪之后保存的路径
 * @param options 裁剪配置             
 */
void onPickFromCaptureWithCrop(Uri outPutUri, CropOptions options);
/**
 * 从相册中获取图片并裁剪
 * @param outPutUri 图片裁剪之后保存的路径
 * @param options 裁剪配置
 */
void onPickFromGalleryWithCrop(Uri outPutUri, CropOptions options);
/**
 * 从文件中获取图片并裁剪
 * @param outPutUri 图片裁剪之后保存的路径
 * @param options 裁剪配置
 */
void onPickFromDocumentsWithCrop(Uri outPutUri, CropOptions options);
/**
 * 图片多选,并裁切
 * @param limit 最多选择图片张数的限制
 * @param options  裁剪配置
 * */
void onPickMultipleWithCrop(int limit, CropOptions options);

压缩图片

copy iconCopydownload iconDownload
 /**
  * 启用图片压缩
  * @param config 压缩图片配置
  * @param showCompressDialog 压缩时是否显示进度对话框
  * @return
  */
 void onEnableCompress(CompressConfig config,boolean showCompressDialog);

获取更高的兼容性

copy iconCopydownload iconDownload
<activity
    android:name=".MainActivity"
    android:screenOrientation="portrait"
    android:configChanges="orientation|keyboardHidden|screenSize"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

关于代码混淆

copy iconCopydownload iconDownload
-keep class com.jph.takephoto.** { *; }
-dontwarn com.jph.takephoto.**

-keep class com.darsh.multipleimageselect.** { *; }
-dontwarn com.darsh.multipleimageselect.**

-keep class com.soundcloud.android.crop.** { *; }
-dontwarn com.soundcloud.android.crop.**

Image picker giving error showing flutter

copy iconCopydownload iconDownload
void takePhoto(ImageSource source) async {
Navigator.pop(context);
final PickedFile = await _picker.pickImage(source: source);
// final f = await PickedFile!.path;

setState(() {
  // ignore: unnecessary_cast
  _imageFile = File(PickedFile!.path); // use with full path
  
});
print(_imageFile!.path);}

Saving an image and displaying it in gallery

copy iconCopydownload iconDownload
  Bundle extras = data.getExtras();
  Bitmap imageBitmap = (Bitmap) extras.get("data");
  imageView.setImageBitmap(imageBitmap);
imageView.setImageURI(Uri.fromFile(photoFile));
  private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q ? Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) : getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }


private void saveToGallery() {
     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.parse("file://" + photoFile.getAbsolutePath()));
        sendBroadcast(intent);
    } else {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, photoFile.getName());
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/*");
        Uri contentUri;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else {
            contentUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
        }
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
        contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
        Uri uri = getContentResolver().insert(contentUri, contentValues);
        OutputStream os = null;
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
            os = getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            contentValues.clear();
            contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
            getContentResolver().update(uri, contentValues, null, null);
        } catch (Exception e) {
            getContentResolver().delete(uri, null, null);
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

}
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external" path="." />
    <external-files-path name="external_files" path="." />
    <cache-path name="cache" path="." />
    <external-cache-path name="external_cache" path="." />
    <files-path name="files" path="." />
</paths>
-----------------------
  Bundle extras = data.getExtras();
  Bitmap imageBitmap = (Bitmap) extras.get("data");
  imageView.setImageBitmap(imageBitmap);
imageView.setImageURI(Uri.fromFile(photoFile));
  private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q ? Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) : getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }


private void saveToGallery() {
     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.parse("file://" + photoFile.getAbsolutePath()));
        sendBroadcast(intent);
    } else {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, photoFile.getName());
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/*");
        Uri contentUri;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else {
            contentUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
        }
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
        contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
        Uri uri = getContentResolver().insert(contentUri, contentValues);
        OutputStream os = null;
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
            os = getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            contentValues.clear();
            contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
            getContentResolver().update(uri, contentValues, null, null);
        } catch (Exception e) {
            getContentResolver().delete(uri, null, null);
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

}
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external" path="." />
    <external-files-path name="external_files" path="." />
    <cache-path name="cache" path="." />
    <external-cache-path name="external_cache" path="." />
    <files-path name="files" path="." />
</paths>
-----------------------
  Bundle extras = data.getExtras();
  Bitmap imageBitmap = (Bitmap) extras.get("data");
  imageView.setImageBitmap(imageBitmap);
imageView.setImageURI(Uri.fromFile(photoFile));
  private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q ? Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) : getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }


private void saveToGallery() {
     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.parse("file://" + photoFile.getAbsolutePath()));
        sendBroadcast(intent);
    } else {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, photoFile.getName());
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/*");
        Uri contentUri;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else {
            contentUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
        }
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
        contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
        Uri uri = getContentResolver().insert(contentUri, contentValues);
        OutputStream os = null;
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
            os = getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            contentValues.clear();
            contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
            getContentResolver().update(uri, contentValues, null, null);
        } catch (Exception e) {
            getContentResolver().delete(uri, null, null);
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

}
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external" path="." />
    <external-files-path name="external_files" path="." />
    <cache-path name="cache" path="." />
    <external-cache-path name="external_cache" path="." />
    <files-path name="files" path="." />
</paths>
-----------------------
  Bundle extras = data.getExtras();
  Bitmap imageBitmap = (Bitmap) extras.get("data");
  imageView.setImageBitmap(imageBitmap);
imageView.setImageURI(Uri.fromFile(photoFile));
  private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q ? Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) : getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }


private void saveToGallery() {
     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.parse("file://" + photoFile.getAbsolutePath()));
        sendBroadcast(intent);
    } else {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, photoFile.getName());
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/*");
        Uri contentUri;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else {
            contentUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
        }
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
        contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
        Uri uri = getContentResolver().insert(contentUri, contentValues);
        OutputStream os = null;
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
            os = getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            contentValues.clear();
            contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
            getContentResolver().update(uri, contentValues, null, null);
        } catch (Exception e) {
            getContentResolver().delete(uri, null, null);
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

}
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external" path="." />
    <external-files-path name="external_files" path="." />
    <cache-path name="cache" path="." />
    <external-cache-path name="external_cache" path="." />
    <files-path name="files" path="." />
</paths>

Error: Required named parameter 'path' must be provided

copy iconCopydownload iconDownload
CameraViewPage({Key? key, required this.path}) : super(key: key);
Navigator.push(context, MaterialPageRoute(builder: (builder)=> CameraViewPage(path: path)));
await _cameraController.takePicture(path: path);
-----------------------
CameraViewPage({Key? key, required this.path}) : super(key: key);
Navigator.push(context, MaterialPageRoute(builder: (builder)=> CameraViewPage(path: path)));
await _cameraController.takePicture(path: path);
-----------------------
CameraViewPage({Key? key, required this.path}) : super(key: key);
Navigator.push(context, MaterialPageRoute(builder: (builder)=> CameraViewPage(path: path)));
await _cameraController.takePicture(path: path);
-----------------------
  void takePhoto(BuildContext context) async {
       final path = join((await getTemporaryDirectory()).path,"${DateTime.now()}.png");
       await _cameraController.takePicture(path);
       Navigator.push(context, MaterialPageRoute(builder: (builder)=> CameraViewPage(path:path)));
      }

Camera permission in delphi 11

copy iconCopydownload iconDownload
PROCEDURE PermissionRequestResult(             Sender : TObject;
                                  const APermissions  : TClassicStringDynArray;
                                  const AGrantResults : TClassicPermissionStatusDynArray);

PROCEDURE DisplayRationale(      Sender             : TObject;
                           const APermissions       : TClassicStringDynArray;
                           const APostRationaleProc : TProc);

error: The argument type 'PickedFile' can't be assigned to the parameter type 'File'. flutter

copy iconCopydownload iconDownload
FileImage(File(_imageFile.path))

The argument type 'Object' can't be assigned to the parameter type 'ImageProvider&lt;Object&gt;?'.- flutter image

copy iconCopydownload iconDownload
       CircleAvatar(
          radius: 80.0,
          backgroundImage: _imageFile == null
              ? AssetImage("assets/pic.jpg") as ImageProvider
              :FileImage(_imageFile),

        ),

-----------------------
CircleAvatar(
      radius: 80.0,
      backgroundImage: _imageFile == null
          ? AssetImage("assets/pic.jpg") as ImageProvider
          : FileImage(_imageFile),
    )

The method 'CreateProfile' isn't defined for the type '_ProfileScreenState'

copy iconCopydownload iconDownload
 Navigator.push(context,
        MaterialPageRoute(builder: (context) => CreateProfile(
key: UniqueKey()))

Android CameraX image capture onImageSaved never runs

copy iconCopydownload iconDownload
 imageCapture.takePicture(ContextCompat.getMainExecutor(requireContext()),object :
        ImageCapture.OnImageCapturedCallback() {
        override fun onCaptureSuccess(image: ImageProxy) {
            super.onCaptureSuccess(image)
            val bitmap =imageProxyToBitmap(image)
            val file  = bitmap?.let {
                AppUtils.saveImage(requireContext(),
                    it,SimpleDateFormat(CameraFragment.FILENAME_FORMAT, 
                 Locale.US).format(System.currentTimeMillis()) + ".png")
            }
            val savedUri = Uri.fromFile(file)

            if (savedUri != null) {
              // here your save image uri path 
            }

        }

        override fun onError(exception: ImageCaptureException) {
            super.onError(exception)

        }

    })
 private fun imageProxyToBitmap(image: ImageProxy): Bitmap {
    val planeProxy = image.planes[0]
    val buffer: ByteBuffer = planeProxy.buffer
    val bytes = ByteArray(buffer.remaining())
    buffer.get(bytes)
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}
  @Throws(IOException::class)
 fun saveImage(context: Context,bitmap: Bitmap,  name: String): File? {
    val saved: Boolean
    var image : File?=null
    val fos: OutputStream? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val resolver: ContentResolver = context.contentResolver
        val contentValues = ContentValues()
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name)
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/")
        val imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        image =File(imageUri?.let { FileUriUtils.getRealPath(context, uri = it) })
        imageUri?.let { resolver.openOutputStream(it) }
    } else {
        val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString() + File.separator
        val file = File(imagesDir)
        if (!file.exists()) {
            file.mkdir()
        }

        image = File(imagesDir, "$name.png")
        FileOutputStream(image)
    }
    saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
    fos?.flush()
    fos?.close()

    return image
}
-----------------------
 imageCapture.takePicture(ContextCompat.getMainExecutor(requireContext()),object :
        ImageCapture.OnImageCapturedCallback() {
        override fun onCaptureSuccess(image: ImageProxy) {
            super.onCaptureSuccess(image)
            val bitmap =imageProxyToBitmap(image)
            val file  = bitmap?.let {
                AppUtils.saveImage(requireContext(),
                    it,SimpleDateFormat(CameraFragment.FILENAME_FORMAT, 
                 Locale.US).format(System.currentTimeMillis()) + ".png")
            }
            val savedUri = Uri.fromFile(file)

            if (savedUri != null) {
              // here your save image uri path 
            }

        }

        override fun onError(exception: ImageCaptureException) {
            super.onError(exception)

        }

    })
 private fun imageProxyToBitmap(image: ImageProxy): Bitmap {
    val planeProxy = image.planes[0]
    val buffer: ByteBuffer = planeProxy.buffer
    val bytes = ByteArray(buffer.remaining())
    buffer.get(bytes)
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}
  @Throws(IOException::class)
 fun saveImage(context: Context,bitmap: Bitmap,  name: String): File? {
    val saved: Boolean
    var image : File?=null
    val fos: OutputStream? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val resolver: ContentResolver = context.contentResolver
        val contentValues = ContentValues()
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name)
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/")
        val imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        image =File(imageUri?.let { FileUriUtils.getRealPath(context, uri = it) })
        imageUri?.let { resolver.openOutputStream(it) }
    } else {
        val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString() + File.separator
        val file = File(imagesDir)
        if (!file.exists()) {
            file.mkdir()
        }

        image = File(imagesDir, "$name.png")
        FileOutputStream(image)
    }
    saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
    fos?.flush()
    fos?.close()

    return image
}
-----------------------
 imageCapture.takePicture(ContextCompat.getMainExecutor(requireContext()),object :
        ImageCapture.OnImageCapturedCallback() {
        override fun onCaptureSuccess(image: ImageProxy) {
            super.onCaptureSuccess(image)
            val bitmap =imageProxyToBitmap(image)
            val file  = bitmap?.let {
                AppUtils.saveImage(requireContext(),
                    it,SimpleDateFormat(CameraFragment.FILENAME_FORMAT, 
                 Locale.US).format(System.currentTimeMillis()) + ".png")
            }
            val savedUri = Uri.fromFile(file)

            if (savedUri != null) {
              // here your save image uri path 
            }

        }

        override fun onError(exception: ImageCaptureException) {
            super.onError(exception)

        }

    })
 private fun imageProxyToBitmap(image: ImageProxy): Bitmap {
    val planeProxy = image.planes[0]
    val buffer: ByteBuffer = planeProxy.buffer
    val bytes = ByteArray(buffer.remaining())
    buffer.get(bytes)
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}
  @Throws(IOException::class)
 fun saveImage(context: Context,bitmap: Bitmap,  name: String): File? {
    val saved: Boolean
    var image : File?=null
    val fos: OutputStream? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val resolver: ContentResolver = context.contentResolver
        val contentValues = ContentValues()
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name)
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/")
        val imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        image =File(imageUri?.let { FileUriUtils.getRealPath(context, uri = it) })
        imageUri?.let { resolver.openOutputStream(it) }
    } else {
        val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString() + File.separator
        val file = File(imagesDir)
        if (!file.exists()) {
            file.mkdir()
        }

        image = File(imagesDir, "$name.png")
        FileOutputStream(image)
    }
    saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
    fos?.flush()
    fos?.close()

    return image
}

Unhandled Exception: type 'XFile' is not a subtype of type 'PickedFile' in type cast

copy iconCopydownload iconDownload
XFile _imageFile; 
-----------------------
 final ImagePicker _picker = ImagePicker();

  Future<File?> takePhoto(ImageSource source) async {
    final XFile? image = await _picker.pickImage(source: source);                  
    
    final File? file = File(image!.path);
    return file;
  }

How can I convert an Image selected from my gallery or camera snapshot from my flutter app to base64, display it before I persist to database

copy iconCopydownload iconDownload
     Image(
                          image: _imageFile == null
                              ? AssetImage("assets/images/user2.png")
                              : Image.memory(bytes).image

                        ),

Community Discussions

Trending Discussions on TakePhoto
  • Image picker giving error showing flutter
  • Saving an image and displaying it in gallery
  • Error: Required named parameter 'path' must be provided
  • Camera permission in delphi 11
  • error: The argument type 'PickedFile' can't be assigned to the parameter type 'File'. flutter
  • The argument type 'Object' can't be assigned to the parameter type 'ImageProvider&lt;Object&gt;?'.- flutter image
  • The method 'CreateProfile' isn't defined for the type '_ProfileScreenState'
  • Unable to access media inside microsoftTeams javascript library
  • Android CameraX image capture onImageSaved never runs
  • Unhandled Exception: type 'XFile' is not a subtype of type 'PickedFile' in type cast
Trending Discussions on TakePhoto

QUESTION

Image picker giving error showing flutter

Asked 2022-Apr-10 at 01:20

I was trying to upload the image to flutter app by using Image picker, all things were working fine but when I try to show the Image in the app it was giving the following error in code: "The argument type 'String' can't be assigned to the parameter type 'File'" this is the function I am calling:

 void takePhoto(ImageSource source) async {
Navigator.pop(context);
final PickedFile = await _picker.pickImage(source: source);
// final f = await PickedFile!.path;

setState(() {
  // ignore: unnecessary_cast
  _imageFile = PickedFile!;
  
});
print(_imageFile!.path);}

and when I print the path so it is giving me correct path but when I try to show the Image so it is giving the error, code for displaying image

 _imageFile!= null ? Image.file(
                      _imageFile!.path
                    ):
                    Text("no image"),

ANSWER

Answered 2022-Apr-10 at 01:20

Try with this

void takePhoto(ImageSource source) async {
Navigator.pop(context);
final PickedFile = await _picker.pickImage(source: source);
// final f = await PickedFile!.path;

setState(() {
  // ignore: unnecessary_cast
  _imageFile = File(PickedFile!.path); // use with full path
  
});
print(_imageFile!.path);}

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

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

Vulnerabilities

No vulnerabilities reported

Install TakePhoto

You can download it from GitHub.
You can use TakePhoto 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 TakePhoto 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

Share this Page

share link
Compare Computer Vision Libraries with Highest Support
Compare Computer Vision Libraries with Highest Security
Compare Computer Vision Libraries with Permissive License
Compare Computer Vision Libraries with Highest Reuse
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.