H5+獲取手機拍照和相冊 vue作數據 base64上傳

//彈出選擇拍照仍是相冊選擇
              addCamera: function() {
						var that = this;
						plus.nativeUI.actionSheet({
								cancel: "取消",
								buttons: [{
									title: "從相冊選擇"
								}, {
									title: "拍照"
								}]
							},
							function(event) {
								if(event.index == 1) {
									that.getGallery();
								} else if(event.index == 2) {
									that.getCamera();
								}
							}
						);
					}

          //拍照
               getCamera: function() {
						var that = this;
						var cmr = plus.camera.getCamera();
						console.log(that.picData.length);
						if(that.picData.length <= 2) {
							cmr.captureImage(function(path) {
								plus.io.resolveLocalFileSystemURL(path, function(entry) {
									var localurl = entry.toLocalURL();

									//將拍照的圖片編碼爲base64
									that.uploadPics(localurl);
								});
							}, function(error) {
								console.log(error.message);
							}, {
								filename: "_doc/camera/", //我是根據文檔寫的
								index: 1 //ios指定主攝像頭
							});
						} else {
							mui.toast("最多隻能上傳三張照片")
						}

					},
              //相冊選擇
                 getGallery: function() {
						var that = this;
						if(that.picData.length <= 2) {
							plus.gallery.pick(function(path) {
								
								//將相冊的圖片編碼爲base64
								that.uploadPics(path);
							}, function(e) {
								console.log("取消選擇圖片");
							}, {
								filename: "_doc/gallery/", //我是根據文檔寫的
								filter: "image"
							});
						} else {
							mui.toast("最多隻能上傳三張照片")
						}

					},
         //編碼爲base64
                  uploadPics: function(url) {
						var img = new Image();
						img.src = url;
						img.onload = function() {
							var that = img;
							var w = that.width,
								h = that.height,
								scale = w / h;
							w = 320 || w;
							h = w / scale;
							var canvas = document.createElement('canvas');
							var ctx = canvas.getContext('2d');
							$(canvas).attr({
								width: w,
								height: h
							});
							ctx.drawImage(that, 0, 0, w, h);
							var base64 = canvas.toDataURL('image/png', 'image/jpeg', 'image/jpg', 1 || 0.8);
							console.log(base64)
						}
					},
相關文章
相關標籤/搜索