반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

welcome to my blog

[Flutter] 갤러리에 이미지 저장하기 본문

Flutter

[Flutter] 갤러리에 이미지 저장하기

_annie_ 2021. 10. 17. 20:00
728x90
    •  

2021.10.16 - [Flutter] - [Flutter] Image Asset 추가하기

  • 구현할 기능 :

- 이미지를 꾹 누르면(LongPress) "저장하시겠습니까?" 팝업 발생

- 저장 / 닫기 버튼 

- 저장 선택시 갤러리에 이미지 저장 후 팝업 닫기

- 닫기 선택시 팝업 닫기

 


사용 라이브러리 :

1. image_gallery_saver https://pub.dev/packages/image_gallery_saver

flutter pub add image_gallery_saver

작성일 기준 1.7.1 ver.

 

2. Dio https://pub.dev/packages/dio

flutter pub add dio

작성일 기준 4.0.0 ver.

 

3. cached_network_image https://pub.dev/packages/cached_network_image

flutter pub add cached_network_image

작성일 기준 3.1.0 ver.

 

import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'dart:typed_data';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';

 

<참고> 

빨간밑줄이 생겼을때 라이브러리 import 하는 방법 : 해당 부분위에서 Option + Enter 하면 쉽게 추가 할 수 있다.

 

  • 권한설정

android/app/src/ + debug & profile

AndroidManifest.xml 의 <application></application> 사이에 다음 코드 추가

android:requestLegacyExternalStorage="true"

 

ios/Runner/Info.plist

Info.plist <dict></dict> 사이에 다음 코드 추가

<key>NSPhotoLibraryAddUsageDescription</key>
<string>Used to demonstrate image picker plugin</string>

 

  • GestureDetector 추가 
GestureDetector(     
	onLongPress: () => showDialog<String>(
		context: context,
		builder: (BuildContext context) => AlertDialog(title: Text("저장하시겠습니까?"),
	        actions: [
				OutlinedButton(onPressed: (){
					_save(context);
				}, child: Text("저장")),
				OutlinedButton(onPressed: () => Navigator.pop(context, 'Cancel'), 
            	child: Text("취소")),
			],)
		),
		child: CachedNetworkImage(
		placeholder: (context, url) => CircularProgressIndicator(),
		imageUrl: article.urlToImage ?? '',
		errorWidget: (context, url, error) =>
			Image.asset("assets/main.png"),
			fit: BoxFit.fill
    )
)

해당 코드에서는 CachedNetworkImage 위젯 상위에 GestureDetector 추가 (원하는 이미지 위젯 상위에 GestrueDetector 추가하기)

Gesture 추가

(참고) onLongPress : 꾹 눌렀을때 이벤트 / onTap : 한번 터치했을때 이벤트

onLongPress에 함수 연결 ---> showDialog<String>()

builder에 AlertDialog 추가 

AlertDialog actions버튼 2개 추가(저장/취소)

저장버튼의 onPressed에는 save 기능과 창닫기 기능 추가

닫기버튼의 onPressed에는 창닫기 기능 추가

 

* error핸들링 부분의 Image.asset 추가방법은 해당블로그의 Image Asset추가하기에 정리해두었음

2021.10.16 - [Flutter] - [Flutter] Image Asset 추가하기

 

[Flutter] Image Asset 추가하기

프로젝트명 우클릭 > assets 폴더 생성 생성한폴더(assets) 내부에 등록하고 싶은 이미지 파일 추가하기 pubspec.yaml 파일 내부에 해당 부분 주석 풀고 이미지 등록 이미지 사용 : Image.asset("assets/main.png"

annhee.tistory.com

 

  • save 함수: (class내부에 추가했음 - build밖)
_save(BuildContext context) async {
    var response = await Dio().get(
        article.urlToImage ?? "",
        options: Options(responseType: ResponseType.bytes));
    final result = await ImageGallerySaver.saveImage(
        Uint8List.fromList(response.data),
        quality: 60,
        name: "hello");

    Navigator.pop(context);
    print(result);
  }

전달인자로 BuildContext 전달받고 마지막에 Navigator.pop(context); 로 창 닫기

 

  • 팝업 화면 : 

 

 

 

gallery_saver 도 있었는데 실패...

728x90
반응형