下面列出了android.os.StrictMode.ThreadPolicy#android.graphics.Bitmap.CompressFormat 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 根据文件的路径获取Video文件缩略图流数据
* @param filePath
* @return
*/
@TargetApi(Build.VERSION_CODES.FROYO)
private InputStream getVideoThumbnailStream(String filePath) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
//创建缩略图
Bitmap bitmap = ThumbnailUtils
.createVideoThumbnail(filePath, MediaStore.Images.Thumbnails.FULL_SCREEN_KIND);
if (bitmap != null) {
//图像转成流传入
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, bos);
return new ByteArrayInputStream(bos.toByteArray());
}
}
return null;
}
/**
* Retrieves {@link java.io.InputStream} of image by URI (image is accessed using {@link android.content.ContentResolver}).
*
* @param imageUri Image URI
* @param extra Auxiliary object which was passed to {@link com.nostra13.universalimageloader.core.DisplayImageOptions.Builder#extraForDownloader(Object)
* DisplayImageOptions.extraForDownloader(Object)}; can be null
* @return {@link java.io.InputStream} of image
* @throws java.io.FileNotFoundException if the provided URI could not be opened
*/
protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException {
ContentResolver res = context.getContentResolver();
Uri uri = Uri.parse(imageUri);
if (isVideoUri(uri)) { // video thumbnail
Long origId = Long.valueOf(uri.getLastPathSegment());
Bitmap bitmap = MediaStore.Video.Thumbnails
.getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null);
if (bitmap != null) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, bos);
return new ByteArrayInputStream(bos.toByteArray());
}
} else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) { // contacts photo
return ContactsContract.Contacts.openContactPhotoInputStream(res, uri, true);
}
return res.openInputStream(uri);
}
public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, output);
if (needRecycle) {
bmp.recycle();
}
byte[] result = output.toByteArray();
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String ouputModifiedBitmap(Bitmap bitmap, Uri uri) throws IOException {
// Create an ExifHelper to save the exif data that is lost during compression
String modifiedPath = getTempDirectoryPath() + "/modified.jpg";
OutputStream os = new FileOutputStream(modifiedPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Some content: URIs do not map to file paths (e.g. picasa).
String realPath = FileHelper.getRealPath(uri, this.cordova);
ExifHelper exif = new ExifHelper();
if (realPath != null && this.encodingType == JPEG) {
try {
exif.createInFile(realPath);
exif.readExifData();
if (this.correctOrientation && this.orientationCorrected) {
exif.resetOrientation();
}
exif.createOutFile(modifiedPath);
exif.writeExifData();
} catch (IOException e) {
e.printStackTrace();
}
}
return modifiedPath;
}
public void saveBitmap(String fileName, Bitmap bitmap) throws IOException {
fileName = fileName.replaceAll("[^\\w]", "");
if (bitmap == null) {
return;
}
String path = getStorageDirectory();
File foldFile = new File(path);
if (!foldFile.exists()) {
foldFile.mkdir();
}
File file = new File(path + File.separator + fileName);
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 80, outputStream);
outputStream.flush();
outputStream.close();
}
public static String saveScreenBitmap(Activity activity) {
Bitmap bitmap = screenShot(activity);
File file = new File(DirectoryPath.getX8LocalSar() + "/" + DateUtil.getStringByFormat(System.currentTimeMillis(), DateUtil.dateFormatYYMMDDHHMMSS) + ".jpeg");
String s = "";
try {
if (!file.exists()) {
if (file.getParentFile().exists()) {
file.createNewFile();
} else {
file.getParentFile().mkdirs();
}
}
if (save(bitmap, file, CompressFormat.JPEG, true)) {
X8ToastUtil.showToast(activity, activity.getString(R.string.x8_ai_fly_sar_save_pic_tip), 0);
}
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, output);
if (needRecycle) {
bmp.recycle();
}
byte[] result = output.toByteArray();
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public void writeBtimapToSD(
Context ctx, String dir, String file, Bitmap img, CompressFormat format)
throws Exception{
if(!hasSDCard()){
return;
}
if (img == null) {
return;
}
String path = dir + EncryptTools.instance().toMD5(file);
File targetFile = new File(path);
if(targetFile.exists()){
return;
}
targetFile.createNewFile();
FileOutputStream fo = new FileOutputStream(path);
img.compress(format, 100, fo);
fo.flush();
fo.close();
}
/**
* Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript.
*
* @param bitmap
*/
public void processPicture(Bitmap bitmap) {
ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
try {
if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) {
byte[] code = jpeg_data.toByteArray();
byte[] output = Base64.encode(code, Base64.DEFAULT);
String js_out = new String(output);
this.callbackContext.success(js_out);
js_out = null;
output = null;
code = null;
}
} catch (Exception e) {
this.failPicture("Error compressing image.");
}
jpeg_data = null;
}
public void saveBitmap(Bitmap bm)
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String currentDateandTime = sdf.format(new Date());
String filename =currentDateandTime + ".jpg";
File diretory = new File(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("File", "") + File.separator + "Pictures");
diretory.mkdirs();
File outputFile = new File(diretory, filename);
FileOutputStream stream = new FileOutputStream(outputFile.toString());
bm.compress(CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
}
catch(Exception e)
{
Log.e("Could not save", e.toString());
}
}
public static Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int offset = 100;
while (baos.toByteArray().length / 1024 > MAX_SIZE) { //循环判断如果压缩后图片是否大于200kb,大于继续压缩
baos.reset();//重置baos即清空baos
image.compress(CompressFormat.JPEG, offset, baos);//这里压缩options%,把压缩后的数据存放到baos中
offset -= 10;//每次都减少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
//把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
return bitmap;
}
public static boolean writeToFile(final File file, final Bitmap bitmap) {
if ((bitmap == null) || (file == null) || file.exists()) {
return false;
}
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(file),
ImageHelper.OUTPUT_BUFFER_SIZE);
return bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
} catch (final IOException e) {
if (AppContext.DEBUG) {
Log.d(ImageHelper.TAG, "writeToFile:" + e.getMessage());
}
} finally {
IOHelper.forceClose(bos);
}
return false;
}
private String ouputModifiedBitmap(Bitmap bitmap, Uri uri) throws IOException {
// Create an ExifHelper to save the exif data that is lost during compression
String modifiedPath = getTempDirectoryPath() + "/modified.jpg";
OutputStream os = new FileOutputStream(modifiedPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Some content: URIs do not map to file paths (e.g. picasa).
String realPath = FileHelper.getRealPath(uri, this.cordova);
ExifHelper exif = new ExifHelper();
if (realPath != null && this.encodingType == JPEG) {
try {
exif.createInFile(realPath);
exif.readExifData();
if (this.correctOrientation && this.orientationCorrected) {
exif.resetOrientation();
}
exif.createOutFile(modifiedPath);
exif.writeExifData();
} catch (IOException e) {
e.printStackTrace();
}
}
return modifiedPath;
}
public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, output);
if (needRecycle) {
bmp.recycle();
}
byte[] result = output.toByteArray();
try {
output.close();
} catch (Exception e) {
Log.e("bmpToByteArray", "bmpToByteArray error", e);
}
return result;
}
/**
* Returns a compressed JPEG byte representation of this Pix.
*
* @param pixs A source pix image.
* @param quality The quality of the compressed image. Valid range is 0-100.
* @param progressive Whether to use progressive compression.
* @return a compressed JPEG byte array representation of the Pix
*/
public static byte[] compressToJpeg(Pix pixs, int quality, boolean progressive) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
if (quality < 0 || quality > 100)
throw new IllegalArgumentException("Quality must be between 0 and 100 (inclusive)");
final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
final Bitmap bmp = WriteFile.writeBitmap(pixs);
bmp.compress(CompressFormat.JPEG, quality, byteStream);
bmp.recycle();
final byte[] encodedData = byteStream.toByteArray();
try {
byteStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return encodedData;
}
final ShareParams shareDataToShareParams(Platform plat) {
if (plat == null || shareParamsMap == null) {
toast("ssdk_oks_share_failed");
return null;
}
try {
String imagePath = R.forceCast(shareParamsMap.get("imagePath"));
Bitmap viewToShare = R.forceCast(shareParamsMap.get("viewToShare"));
if (TextUtils.isEmpty(imagePath) && viewToShare != null && !viewToShare.isRecycled()) {
String path = R.getCachePath(plat.getContext(), "screenshot");
File ss = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
FileOutputStream fos = new FileOutputStream(ss);
viewToShare.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
shareParamsMap.put("imagePath", ss.getAbsolutePath());
}
} catch (Throwable t) {
t.printStackTrace();
toast("ssdk_oks_share_failed");
return null;
}
return new ShareParams(shareParamsMap);
}
private String ouputModifiedBitmap(Bitmap bitmap, Uri uri) throws IOException {
// Create an ExifHelper to save the exif data that is lost during compression
String modifiedPath = getTempDirectoryPath() + "/modified.jpg";
OutputStream os = new FileOutputStream(modifiedPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Some content: URIs do not map to file paths (e.g. picasa).
String realPath = FileHelper.getRealPath(uri, this.cordova);
ExifHelper exif = new ExifHelper();
if (realPath != null && this.encodingType == JPEG) {
try {
exif.createInFile(realPath);
exif.readExifData();
if (this.correctOrientation && this.orientationCorrected) {
exif.resetOrientation();
}
exif.createOutFile(modifiedPath);
exif.writeExifData();
} catch (IOException e) {
e.printStackTrace();
}
}
return modifiedPath;
}
final ShareParams shareDataToShareParams(Platform plat) {
if (plat == null || shareParamsMap == null) {
toast("ssdk_oks_share_failed");
return null;
}
try {
String imagePath = ResHelper.forceCast(shareParamsMap.get("imagePath"));
Bitmap viewToShare = ResHelper.forceCast(shareParamsMap.get("viewToShare"));
if (TextUtils.isEmpty(imagePath) && viewToShare != null && !viewToShare.isRecycled()) {
String path = ResHelper.getCachePath(plat.getContext(), "screenshot");
File ss = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
FileOutputStream fos = new FileOutputStream(ss);
viewToShare.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
shareParamsMap.put("imagePath", ss.getAbsolutePath());
}
} catch (Throwable t) {
t.printStackTrace();
toast("ssdk_oks_share_failed");
return null;
}
return new ShareParams(shareParamsMap);
}
final ShareParams shareDataToShareParams(Platform plat) {
if (plat == null || shareParamsMap == null) {
toast("ssdk_oks_share_failed");
return null;
}
try {
String imagePath = R.forceCast(shareParamsMap.get("imagePath"));
Bitmap viewToShare = R.forceCast(shareParamsMap.get("viewToShare"));
if (TextUtils.isEmpty(imagePath) && viewToShare != null && !viewToShare.isRecycled()) {
String path = R.getCachePath(plat.getContext(), "screenshot");
File ss = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
FileOutputStream fos = new FileOutputStream(ss);
viewToShare.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
shareParamsMap.put("imagePath", ss.getAbsolutePath());
}
} catch (Throwable t) {
t.printStackTrace();
toast("ssdk_oks_share_failed");
return null;
}
return new ShareParams(shareParamsMap);
}
public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, output);
if (needRecycle) {
bmp.recycle();
}
byte[] result = output.toByteArray();
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
public void onBitmapLoaded(Bitmap bitmap, LoadedFrom arg1) {
mDetailImageView.setImageBitmap(bitmap);
mDetailPicture = bitmap;
mLoadingGif.setVisibility(View.INVISIBLE);
mPrePlayButton.setVisibility(View.VISIBLE);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
mDetailPicture.compress(CompressFormat.JPEG, 100, bytes);
File file = new File(mContext.getCacheDir(), "toshare.jpg");
try {
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
final ShareParams shareDataToShareParams(Platform plat) {
if (plat == null || shareParamsMap == null) {
toast("ssdk_oks_share_failed");
return null;
}
try {
String imagePath = ResHelper.forceCast(shareParamsMap.get("imagePath"));
Bitmap viewToShare = ResHelper.forceCast(shareParamsMap.get("viewToShare"));
if (TextUtils.isEmpty(imagePath) && viewToShare != null && !viewToShare.isRecycled()) {
String path = ResHelper.getCachePath(plat.getContext(), "screenshot");
File ss = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
FileOutputStream fos = new FileOutputStream(ss);
viewToShare.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
shareParamsMap.put("imagePath", ss.getAbsolutePath());
}
} catch (Throwable t) {
t.printStackTrace();
toast("ssdk_oks_share_failed");
return null;
}
return new ShareParams(shareParamsMap);
}
public static File getScaledImageFileWithMD5(File imageFile, String mimeType) {
String filePath = imageFile.getPath();
if (!isInvalidPictureFile(mimeType)) {
return null;
}
String tempFilePath = getTempFilePath(FileUtil.getExtensionName(filePath));
Log.i("ImageUtil", "tempFilePath:"+tempFilePath);
File tempImageFile = AttachmentStore.create(tempFilePath);
if (tempImageFile == null) {
return null;
}
CompressFormat compressFormat = CompressFormat.JPEG;
// 压缩数值由第三方开发者自行决定
int maxWidth = 720;
int quality = 60;
if (ImageUtil.scaleImage(imageFile, tempImageFile, maxWidth, compressFormat, quality)) {
return tempImageFile;
} else {
return null;
}
}
public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, output);
if (needRecycle) {
bmp.recycle();
}
byte[] result = output.toByteArray();
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* Extracts the icon from an APK and writes it to the repo as a PNG
*/
private void copyIconToRepo(Drawable drawable, String packageName, int versionCode) {
Bitmap bitmap;
if (drawable instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) drawable).getBitmap();
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
}
File png = getIconFile(packageName, versionCode);
OutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(png));
bitmap.compress(CompressFormat.PNG, 100, out);
out.close();
} catch (Exception e) {
Log.e(TAG, "Error copying icon to repo", e);
}
}
public static String makeThumbnail(File imageFile) {
String thumbFilePath = StorageUtil.getWritePath(imageFile.getName(), StorageType.TYPE_THUMB_IMAGE);
File thumbFile = AttachmentStore.create(thumbFilePath);
if (thumbFile == null) {
return null;
}
boolean result = scaleThumbnail(
imageFile,
thumbFile,
MsgViewHolderThumbBase.getImageMaxEdge(),
MsgViewHolderThumbBase.getImageMinEdge(),
CompressFormat.JPEG,
60);
if (!result) {
AttachmentStore.delete(thumbFilePath);
return null;
}
return thumbFilePath;
}
/**
* 根据文件类型获得CompressFormat.
*
* @Description:
* @Date 2014-3-7
*/
private CompressFormat getCompressFormat(String url) {
String lowerUrl = url.toLowerCase(Locale.ENGLISH);
if (lowerUrl.endsWith(".jpg")) {
return CompressFormat.JPEG;
} else if (lowerUrl.endsWith(".png")) {
return CompressFormat.PNG;
}
return CompressFormat.JPEG;
}
public RemotePackageInfo (Drawable drawable, String packageName, String label)
{
java.io.ByteArrayOutputStream jByteArray = new java.io.ByteArrayOutputStream() ;
Bitmap.createScaledBitmap(((BitmapDrawable) drawable).getBitmap(),65,65,true).compress(CompressFormat.PNG, 100, jByteArray);
images = jByteArray.toByteArray();
this.packageName = packageName;
this.label = label;
}
@Deprecated
public static void writeBitmapAttribute(XmlSerializer out, String name, Bitmap value)
throws IOException {
if (value != null) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
value.compress(CompressFormat.PNG, 90, os);
writeByteArrayAttribute(out, name, os.toByteArray());
}
}
@TargetApi(Build.VERSION_CODES.FROYO)
private InputStream getVideoThumbnailStream(String filePath) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
Bitmap bitmap = ThumbnailUtils
.createVideoThumbnail(filePath, MediaStore.Images.Thumbnails.FULL_SCREEN_KIND);
if (bitmap != null) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, bos);
return new ByteArrayInputStream(bos.toByteArray());
}
}
return null;
}