Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Supported custom album name #271

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,15 @@ class ImageGallerySaverPlugin : FlutterPlugin, MethodCallHandler {
val image = call.argument<ByteArray?>("imageBytes")
val quality = call.argument<Int?>("quality")
val name = call.argument<String?>("name")
val albumName = call.argument<String?>("albumName")

result.success(
saveImageToGallery(
BitmapFactory.decodeByteArray(
image ?: ByteArray(0),
0,
image?.size ?: 0
), quality, name
), quality, name, albumName
)
)
}
Expand All @@ -69,8 +70,9 @@ class ImageGallerySaverPlugin : FlutterPlugin, MethodCallHandler {
methodChannel.setMethodCallHandler(null);
}

private fun generateUri(extension: String = "", name: String? = null): Uri? {
private fun generateUri(extension: String = "", name: String? = null, albumName: String? = null): Uri? {
var fileName = name ?: System.currentTimeMillis().toString()
var albumName = if (albumName == null) Environment.DIRECTORY_PICTURES else "${Environment.DIRECTORY_PICTURES}/$albumName"
val mimeType = getMIMEType(extension)
val isVideo = mimeType?.startsWith("video")==true

Expand All @@ -86,7 +88,7 @@ class ImageGallerySaverPlugin : FlutterPlugin, MethodCallHandler {
put(
MediaStore.MediaColumns.RELATIVE_PATH, when {
isVideo -> Environment.DIRECTORY_MOVIES
else -> Environment.DIRECTORY_PICTURES
else -> albumName
}
)
if (!TextUtils.isEmpty(mimeType)) {
Expand Down Expand Up @@ -148,7 +150,8 @@ class ImageGallerySaverPlugin : FlutterPlugin, MethodCallHandler {
private fun saveImageToGallery(
bmp: Bitmap?,
quality: Int?,
name: String?
name: String?,
albumName: String?
): HashMap<String, Any?> {
// check parameters
if (bmp == null || quality == null) {
Expand All @@ -161,7 +164,7 @@ class ImageGallerySaverPlugin : FlutterPlugin, MethodCallHandler {
var fos: OutputStream? = null
var success = false
try {
fileUri = generateUri("jpg", name = name)
fileUri = generateUri("jpg", name = name , albumName = albumName)
if (fileUri != null) {
fos = context.contentResolver.openOutputStream(fileUri)
if (fos != null) {
Expand Down
33 changes: 27 additions & 6 deletions ios/Classes/SwiftImageGallerySaverPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ public class SwiftImageGallerySaverPlugin: NSObject, FlutterPlugin {
let image = UIImage(data: imageData),
let quality = arguments["quality"] as? Int,
let _ = arguments["name"],
let albumName = arguments["albumName"] as? String,
let isReturnImagePath = arguments["isReturnImagePathOfIOS"] as? Bool
else { return }
let newImage = image.jpegData(compressionQuality: CGFloat(quality / 100))!
saveImage(UIImage(data: newImage) ?? image, isReturnImagePath: isReturnImagePath)
saveImage(UIImage(data: newImage) ?? image, isReturnImagePath: isReturnImagePath , customAlbumName: albumName)
} else if (call.method == "saveFileToGallery") {
guard let arguments = call.arguments as? [String: Any],
let path = arguments["file"] as? String,
Expand Down Expand Up @@ -75,17 +76,29 @@ public class SwiftImageGallerySaverPlugin: NSObject, FlutterPlugin {
})
}

func saveImage(_ image: UIImage, isReturnImagePath: Bool) {
if !isReturnImagePath {
func saveImage(_ image: UIImage, isReturnImagePath: Bool , customAlbumName: String) {
if !isReturnImagePath && customAlbumName == "" {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(didFinishSavingImage(image:error:contextInfo:)), nil)
return
}

var imageIds: [String] = []

PHPhotoLibrary.shared().performChanges( {
var assetCollectionChangeRequest: PHAssetCollectionChangeRequest?
let assetCollection = self.fetchAssetCollectionForAlbum(customAlbumName)

if assetCollection == nil {
assetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: customAlbumName)
} else {
assetCollectionChangeRequest = PHAssetCollectionChangeRequest(for: assetCollection!)
}

let req = PHAssetChangeRequest.creationRequestForAsset(from: image)
if let imageId = req.placeholderForCreatedAsset?.localIdentifier {
let assetPlaceholder = req.placeholderForCreatedAsset
assetCollectionChangeRequest?.addAssets([assetPlaceholder!] as NSFastEnumeration)

if let imageId = assetPlaceholder?.localIdentifier {
imageIds.append(imageId)
}
}, completionHandler: { [unowned self] (success, error) in
Expand All @@ -100,15 +113,23 @@ public class SwiftImageGallerySaverPlugin: NSObject, FlutterPlugin {
imageAsset.requestContentEditingInput(with: options) { [unowned self] (contentEditingInput, info) in
if let urlStr = contentEditingInput?.fullSizeImageURL?.absoluteString {
self.saveResult(isSuccess: true, filePath: urlStr)
}
}
}
}
}
} else {
self.saveResult(isSuccess: false, error: self.errorMessage)
}
}
})
}

func fetchAssetCollectionForAlbum(_ albumName: String) -> PHAssetCollection? {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
let fetchResult: PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

return fetchResult.firstObject
}

func saveImageAtFileUrl(_ url: String, isReturnImagePath: Bool) {
if !isReturnImagePath {
Expand Down
2 changes: 2 additions & 0 deletions lib/image_gallery_saver.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ class ImageGallerySaver {
static FutureOr<dynamic> saveImage(Uint8List imageBytes,
{int quality = 80,
String? name,
String? albumName = '',
bool isReturnImagePathOfIOS = false}) async {
final result =
await _channel.invokeMethod('saveImageToGallery', <String, dynamic>{
'imageBytes': imageBytes,
'quality': quality,
'name': name,
'albumName': albumName,
'isReturnImagePathOfIOS': isReturnImagePathOfIOS
});
return result;
Expand Down