|
4 | 4 | import android.graphics.Bitmap; |
5 | 5 | import android.graphics.BitmapFactory; |
6 | 6 | import android.graphics.Matrix; |
| 7 | +import android.os.Environment; |
7 | 8 |
|
| 9 | +import java.io.File; |
| 10 | +import java.io.FileNotFoundException; |
| 11 | +import java.io.FileOutputStream; |
| 12 | +import java.io.IOException; |
8 | 13 | import java.io.InputStream; |
| 14 | +import java.util.UUID; |
9 | 15 |
|
10 | 16 | public final class BitmapLess { |
11 | 17 |
|
@@ -162,4 +168,54 @@ public final class BitmapLess { |
162 | 168 |
|
163 | 169 | return bitmap; |
164 | 170 | } |
| 171 | + |
| 172 | + /** |
| 173 | + * 保存到本地,默认路径/mnt/sdcard/<package>/save/ |
| 174 | + * @param bitmap |
| 175 | + * @param format |
| 176 | + * @param quality |
| 177 | + * @param context |
| 178 | + * @return |
| 179 | + */ |
| 180 | + public static String $save(Bitmap bitmap, Bitmap.CompressFormat format, int quality, Context context) { |
| 181 | + if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { |
| 182 | + return null; |
| 183 | + } |
| 184 | + |
| 185 | + File dir = new File(Environment.getExternalStorageDirectory() + "/" + context.getPackageName() + "/save/"); |
| 186 | + if (!dir.exists()) { |
| 187 | + dir.mkdirs(); |
| 188 | + } |
| 189 | + File destFile = new File(dir, UUID.randomUUID().toString()); |
| 190 | + return $save(bitmap, format, quality, destFile); |
| 191 | + } |
| 192 | + |
| 193 | + /** |
| 194 | + * 保存到本地destFile |
| 195 | + * @param bitmap |
| 196 | + * @param format |
| 197 | + * @param quality |
| 198 | + * @param destFile |
| 199 | + * @return |
| 200 | + */ |
| 201 | + public static String $save(Bitmap bitmap, Bitmap.CompressFormat format, int quality, File destFile) { |
| 202 | + try { |
| 203 | + FileOutputStream out = new FileOutputStream(destFile); |
| 204 | + if (bitmap.compress(format, quality, out)) { |
| 205 | + out.flush(); |
| 206 | + out.close(); |
| 207 | + } |
| 208 | + |
| 209 | + if (bitmap != null && !bitmap.isRecycled()) { |
| 210 | + bitmap.recycle(); |
| 211 | + } |
| 212 | + |
| 213 | + return destFile.getAbsolutePath(); |
| 214 | + } catch (FileNotFoundException e) { |
| 215 | + e.printStackTrace(); |
| 216 | + } catch (IOException e) { |
| 217 | + e.printStackTrace(); |
| 218 | + } |
| 219 | + return null; |
| 220 | + } |
165 | 221 | } |
0 commit comments