CompressUtils.uts 8.9 KB
Newer Older
1
import {
DCloud-yyl's avatar
DCloud-yyl 已提交
2 3
	CompressImageSuccess, CompressImageOptions,
	CompressVideoOptions, CompressVideoSuccess
4 5
} from "../../interface.uts"
import {
DCloud-yyl's avatar
DCloud-yyl 已提交
6 7
	UniError_CompressVideo,UniError_CompressImage,
	MediaErrorImpl
8 9 10 11 12 13 14 15 16 17 18 19 20
} from "../../unierror.uts"
import TextUtils from 'android.text.TextUtils';
import File from 'java.io.File';
import BitmapFactory from 'android.graphics.BitmapFactory';
import Bitmap from 'android.graphics.Bitmap';
import Matrix from 'android.graphics.Matrix';
import FileOutputStream from 'java.io.FileOutputStream';
import ExifInterface from 'io.dcloud.uts.util.ExifInterface';
import Field from 'java.lang.reflect.Field';
import MediaTranscoder from 'io.dcloud.uts.androidtranscoder.MediaTranscoder';
import MediaFormatStrategyPresets from 'io.dcloud.uts.androidtranscoder.format.MediaFormatStrategyPresets';
import Listener from 'io.dcloud.uts.androidtranscoder.MediaTranscoder.Listener';

DCloud-yyl's avatar
DCloud-yyl 已提交
21
const mediaCachePath = UTSAndroid.getAppCachePath()+"uni-media/"
22 23 24 25
// export function threadCompress() {
// }
export function transcodeImage(options : CompressImageOptions) {
	if (options.src.length == 0) {
DCloud-yyl's avatar
DCloud-yyl 已提交
26 27 28
		let error = new MediaErrorImpl(1101003, UniError_CompressImage);
		options.fail?.(error)
		options.complete?.(error)
29 30 31 32 33 34
		return
	}
	let compressOption = new CompressOptions()
	compressOption.src = UTSAndroid.convert2AbsFullPath(options.src)
	let srcFile = new File(compressOption.src)
	if (!srcFile.exists()) {
DCloud-yyl's avatar
DCloud-yyl 已提交
35 36 37
		let error = new MediaErrorImpl(1101003, UniError_CompressImage);
		options.fail?.(error)
		options.complete?.(error)
38 39 40 41 42 43 44 45 46 47 48
		return
	}
	if (options.quality != null && options.quality! > 0) {
		compressOption.quality = options.quality!
	}
	if (options.rotate != null && options.rotate! >= 0) {
		compressOption.rotate = options.rotate!
	}
	var widthStr = ""
	var heightStr = ""
	if (options.compressedWidth != null) {
DCloud-yyl's avatar
DCloud-yyl 已提交
49
		compressOption.width = options.compressedWidth!
50 51 52 53
	} else {
		widthStr = TextUtils.isEmpty(options.width) ? "auto" : options.width!
	}
	if (options.compressedHeight != null) {
DCloud-yyl's avatar
DCloud-yyl 已提交
54
		compressOption.height = options.compressedHeight!
55 56 57
	} else {
		heightStr = TextUtils.isEmpty(options.height) ? "auto" : options.height!
	}
DCloud-yyl's avatar
DCloud-yyl 已提交
58 59 60
	if (compressOption.width <= 0 || compressOption.height <= 0) {
		getHeightAndWidth(compressOption, widthStr, heightStr)
	}
61 62 63 64 65 66 67 68 69 70 71 72 73
	let bitmapOptions = new BitmapFactory.Options()
	bitmapOptions.inJustDecodeBounds = false;
	if (srcFile.length() > 1500000) {
		bitmapOptions.inSampleSize = 2
	} else {
		bitmapOptions.inSampleSize = 1
	}
	var srcBitmap : Bitmap | null = null
	try {
		srcBitmap = BitmapFactory.decodeFile(compressOption.src, bitmapOptions)
	} catch (e) {
	}
	if (srcBitmap == null) {
DCloud-yyl's avatar
DCloud-yyl 已提交
74 75 76
		let error = new MediaErrorImpl(1101009, UniError_CompressImage);
		options.fail?.(error)
		options.complete?.(error)
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
		return
	}

	if (compressOption.isZoom && compressOption.width > 0 && compressOption.height > 0) {
		let matrix = new Matrix()
		let scaleW = compressOption.width / srcBitmap.getWidth()
		let scaleH = compressOption.height / srcBitmap.getHeight()
		matrix.setScale(scaleW.toFloat(), scaleH.toFloat())
		srcBitmap = Bitmap.createBitmap(srcBitmap!, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, false)
	}
	if (compressOption.rotate > 0) {
		let matrix = new Matrix()
		matrix.postRotate(compressOption.rotate.toFloat())
		srcBitmap = Bitmap.createBitmap(srcBitmap!, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, false)
	}
	// 保存
DCloud-yyl's avatar
DCloud-yyl 已提交
93
	let destPath = mediaCachePath + System.currentTimeMillis() + ".jpg"
94 95 96 97 98 99 100 101 102 103 104 105
	let destFile = new File(destPath)
	if (!destFile.getParentFile().exists()) {
		destFile.getParentFile().mkdirs()
	}
	try {
		let fos = new FileOutputStream(destFile)
		srcBitmap!.compress(Bitmap.CompressFormat.JPEG, compressOption.quality.toInt(), fos);
		fos.close()
		if (!srcBitmap!.isRecycled()) {
			srcBitmap!.recycle()
		}
		saveExif(options.src, destPath)
DCloud-yyl's avatar
DCloud-yyl 已提交
106
		let success : CompressImageSuccess = { "tempFilePath": "file://" + destPath }
107 108 109
		options.success?.(success)
		options.complete?.(success)
	} catch (ex) {
DCloud-yyl's avatar
DCloud-yyl 已提交
110 111 112
		let error = new MediaErrorImpl(1101009, UniError_CompressImage);
		options.fail?.(error)
		options.complete?.(error)
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
	}
}

function saveExif(oldFilePath : string, newFilePath : string) {
	try {
		let oldExif = new ExifInterface(oldFilePath);
		let newExif = new ExifInterface(newFilePath);
		let cls = oldExif.javaClass;
		let fields = cls.getFields();
		fields.forEach((field : Field) => {
			let fieldName = field.getName();
			if (!TextUtils.isEmpty(fieldName) && fieldName.startsWith("TAG")) {
				var o = field.get(cls);
				if (o != null) {
					var fieldValue = o.toString();
					var attribute = oldExif.getAttribute(fieldValue);
					if (attribute != null) {
						newExif.setAttribute(fieldValue, attribute);
					}
				}
			}
		})
		// for (Field field : fields) {

		// }
		newExif.saveAttributes();
	} catch (e) {

	}
}

function getHeightAndWidth(compressOption : CompressOptions, widthStr : string, heightStr : string) {
	let bopt = new BitmapFactory.Options()
	bopt.inJustDecodeBounds = true
	BitmapFactory.decodeFile(compressOption.src, bopt)
	let bitmapWidth = bopt.outWidth
	let bitmapHeight = bopt.outHeight
	if (bitmapHeight <= 0 || bitmapWidth <= 0) {
		return
	}
	if (widthStr.toLowerCase() == "auto" && heightStr.toLowerCase() == "auto") {
		compressOption.isZoom = false
		compressOption.width = bitmapWidth
		compressOption.height = bitmapHeight
	} else if (widthStr.toLowerCase() == "auto") {
		compressOption.isZoom = true
		compressOption.height = str2Float(heightStr, bitmapHeight, bitmapHeight)
		compressOption.width = bitmapWidth * compressOption.height / bitmapHeight
	} else if (heightStr.toLowerCase() == "auto") {
		compressOption.isZoom = true
		compressOption.width = str2Float(widthStr, bitmapWidth, bitmapWidth)
		compressOption.height = bitmapHeight * compressOption.width / bitmapWidth
	} else {
		compressOption.isZoom = true
		compressOption.width = str2Float(widthStr, bitmapWidth, bitmapWidth)
		compressOption.height = str2Float(heightStr, bitmapHeight, bitmapHeight)
	}
}

function str2Float(valuestr : string, realValue : number, defValue : number) : number {
	if (TextUtils.isEmpty(valuestr)) {
		return defValue
	}
	valuestr = valuestr.toLowerCase()
	if (valuestr.endsWith("px")) {
DCloud-yyl's avatar
DCloud-yyl 已提交
178
		valuestr == valuestr.substring(0, valuestr.length - 2);
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
	}
	try {
		return Integer.parseInt(valuestr)
	} catch (e) {
		if (valuestr.endsWith("%")) {
			valuestr = valuestr.substring(0, valuestr.length - 1)
		}
		try {
			return realValue * Integer.parseInt(valuestr) / 100
		} catch (e) {
			return defValue
		}
	}
}

class CompressOptions {
	src : string = ""
	dst : string = ""
	format : string = ""
	quality : number = 80
	width : number = 0
	height : number = 0
	rotate : number = 0
	isZoom : boolean = false
}

export function transcodeVideo(options : CompressVideoOptions) {
	let inPath = UTSAndroid.convert2AbsFullPath(options.src)
	let inFile = new File(inPath)
	if (!inFile.exists()) {
DCloud-yyl's avatar
DCloud-yyl 已提交
209 210 211
		let error = new MediaErrorImpl(1101003, UniError_CompressVideo);
		options.fail?.(error)
		options.complete?.(error)
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
		return
	}
	var compressLevel = 1
	switch (options.quality) {
		case "low":
			compressLevel = 3
			break
		case "medium":
			compressLevel = 2
			break
		default:
			compressLevel = 1
			break
	}

	var resolution = options.resolution?.toDouble();

	if (resolution == null) {
		resolution = 1.0
	} else if (resolution! > 1 || resolution! <= 0) {
		resolution = 1.0
	}
DCloud-yyl's avatar
DCloud-yyl 已提交
234 235
	let fileName = getFileName(inPath);
	let outPath = mediaCachePath + (fileName == "" ? (System.currentTimeMillis() + ".mp4") : fileName)
236 237 238 239 240 241 242 243
	let outFile = new File(outPath)
	if (!outFile.getParentFile().exists()) {
		outFile.getParentFile().mkdirs()
	}

	MediaTranscoder.getInstance().transcodeVideo(inPath, outPath, MediaFormatStrategyPresets.createAndroid720pStrategy(compressLevel, resolution!), new MediaTranscoderListener(inPath, outPath, options))
}

DCloud-yyl's avatar
DCloud-yyl 已提交
244 245 246 247 248 249 250 251
function getFileName(path : string) : string {
	const array = path.split("/")
	if (array.length > 0) {
		return array[array.length - 1]
	}
	return ""
}

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
class MediaTranscoderListener implements Listener {
	inPath : string
	outPath : string
	options : CompressVideoOptions
	constructor(inPath : string, outPath : string, options : CompressVideoOptions) {
		this.inPath = inPath
		this.outPath = outPath;
		this.options = options
	}
	override onTranscodeProgress(progress : Double) {

	}

	override onTranscodeCompleted() {
		let outFile = new File(this.outPath)
		if (outFile.exists()) {
DCloud-yyl's avatar
DCloud-yyl 已提交
268
			let success : CompressVideoSuccess = {
269 270 271 272 273 274
				tempFilePath: "file://" + this.outPath,
				size: outFile.length()
			}
			this.options.success?.(success)
			this.options.complete?.(success)
		} else {
DCloud-yyl's avatar
DCloud-yyl 已提交
275
			let error = new MediaErrorImpl(1101004, UniError_CompressVideo);
276 277 278 279 280 281
			this.options.fail?.(error)
			this.options.complete?.(error)
		}
	}

	override onTranscodeCanceled() {
DCloud-yyl's avatar
DCloud-yyl 已提交
282
		let error = new MediaErrorImpl(1101004, UniError_CompressVideo);
283 284 285 286 287
		this.options.fail?.(error)
		this.options.complete?.(error)
	}

	override onTranscodeFailed(exception : Exception) {
DCloud-yyl's avatar
DCloud-yyl 已提交
288
		let error = new MediaErrorImpl(1101010, UniError_CompressVideo);
289 290 291 292
		this.options.fail?.(error)
		this.options.complete?.(error)
	}
}