I trying capture image and set water mark from onActivityResult method is fragment from my code.
Private void savingCapturedImage() {
long date = System.currentTimeMillis();
Date data = new Date(date);
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera", "mobiliskaita.JPG");
Uri imagePath = Uri.fromFile(file);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imagePath);
System.out.println("bitmap: " + bitmap.getWidth() + " " + bitmap.getHeight());
file.delete();
bitmap = mark(bitmap, String.valueOf(data), 100, 200, 100, false);
bitmap = mark(bitmap, TheGlobals.partneriaiValue, 100, 310, 100, false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
bitmap.recycle();
File fileOutput = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera", photoName());
fileOutput.createNewFile();
FileOutputStream fo = new FileOutputStream(fileOutput);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
private Bitmap mark(Bitmap src, String watermark, int x, int y, int size, boolean underline) {
int w = src.getWidth();
int h = src.getHeight();
Point _p = new Point();
_p.x = x;
_p.y = y;
final float scale = getResources().getDisplayMetrics().density;
int p = (int) (900 * scale + 0.5f);
Bitmap result = Bitmap.createScaledBitmap(src, p, p, true);
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(R.dimen.default_text_size);
paint.setAntiAlias(true);
paint.setUnderlineText(underline);
canvas.drawText(watermark, _p.x, _p.y, paint);
return result;
}
It's working but then i have camer with 8 or more megapixels, i get out of memory expection. Maybe someone can help my solve this problem?
The bitmap from the camera is going to be big, if you're only going to save it as 900x900, then you may have to use another method of reading it (not MediaStore.Images.Media.getBitmap()), one where you can set the inSampleSize: http://developer.android.com/reference/android/graphics/BitmapFactory.html#decodeFile(java.lang.String, android.graphics.BitmapFactory.Options)
You could also recycle src in mark() after you've drawn it to the canvas. At the moment you are creating 2 900x900dp bitmaps, so merging the 2 calls to mark might also help.
Related
I'm getting an image from gallery into a layout , then I'm getting the bitmap of that layout by using getBitmap(), after getting bitmap I'm saving the image into device storage by using saveImage().
After getting bitmap and saving the bitmap, the quality and pixel of that bitmap reduces too much as shown in the pictureSaved image AND Orignal image
Here is the code for getting and saving bitmap
private Bitmap getBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
Toast.makeText(this, "Something Wrong", Toast.LENGTH_SHORT).show();
return null;
}
Bitmap lastimage = Bitmap.createBitmap(cacheBitmap);
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
//2048x2048 resolution
int newWidth = 2048;
int newHeight = 2048;
int width = lastimage.getWidth();
int height = lastimage.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(lastimage, 0, 0, width, height, matrix, true);
lastimage.recycle();
saveImage(resizedBitmap);
return resizedBitmap;
}
For Saving:
private void saveImage (Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/NewFolder");
myDir.mkdirs();
String fname = "Image-.png";
File file = new File(myDir, fname);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks for anyone's help.
I'm getting preview frames using OnImageAvailableListener:
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
try {
image = reader.acquireLatestImage();
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[0].getBuffer();
byte[] data = new byte[buffer.capacity()];
buffer.get(data);
//data.length=332803; width=3264; height=2448
Log.e(TAG, "data.length=" + data.length + "; width=" + image.getWidth() + "; height=" + image.getHeight());
//TODO data processing
} catch (Exception e) {
e.printStackTrace();
}
if (image != null) {
image.close();
}
}
Each time length of data is different but image width and height are the same.
Main problem: data.length is too small for such resolution as 3264x2448.
Size of data array should be 3264*2448=7,990,272, not 300,000 - 600,000.
What is wrong?
imageReader = ImageReader.newInstance(3264, 2448, ImageFormat.JPEG, 5);
I solved this problem by using YUV_420_888 image format and converting it to JPEG image format manually.
imageReader = ImageReader.newInstance(MAX_PREVIEW_WIDTH, MAX_PREVIEW_HEIGHT,
ImageFormat.YUV_420_888, 5);
imageReader.setOnImageAvailableListener(this, null);
Surface imageSurface = imageReader.getSurface();
List<Surface> surfaceList = new ArrayList<>();
//...add other surfaces
previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
previewRequestBuilder.addTarget(imageSurface);
surfaceList.add(imageSurface);
cameraDevice.createCaptureSession(surfaceList,
new CameraCaptureSession.StateCallback() {
//...implement onConfigured, onConfigureFailed for StateCallback
}, null);
#Override
public void onImageAvailable(ImageReader reader) {
Image image = reader.acquireLatestImage();
if (image != null) {
//converting to JPEG
byte[] jpegData = ImageUtils.imageToByteArray(image);
//write to file (for example ..some_path/frame.jpg)
FileManager.writeFrame(FILE_NAME, jpegData);
image.close();
}
}
public final class ImageUtil {
public static byte[] imageToByteArray(Image image) {
byte[] data = null;
if (image.getFormat() == ImageFormat.JPEG) {
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[0].getBuffer();
data = new byte[buffer.capacity()];
buffer.get(data);
return data;
} else if (image.getFormat() == ImageFormat.YUV_420_888) {
data = NV21toJPEG(
YUV_420_888toNV21(image),
image.getWidth(), image.getHeight());
}
return data;
}
private static byte[] YUV_420_888toNV21(Image image) {
byte[] nv21;
ByteBuffer yBuffer = image.getPlanes()[0].getBuffer();
ByteBuffer vuBuffer = image.getPlanes()[2].getBuffer();
int ySize = yBuffer.remaining();
int vuSize = vuBuffer.remaining();
nv21 = new byte[ySize + vuSize];
yBuffer.get(nv21, 0, ySize);
vuBuffer.get(nv21, ySize, vuSize);
return nv21;
}
private static byte[] NV21toJPEG(byte[] nv21, int width, int height) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
YuvImage yuv = new YuvImage(nv21, ImageFormat.NV21, width, height, null);
yuv.compressToJpeg(new Rect(0, 0, width, height), 100, out);
return out.toByteArray();
}
}
public final class FileManager {
public static void writeFrame(String fileName, byte[] data) {
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
bos.write(data);
bos.flush();
bos.close();
// Log.e(TAG, "" + data.length + " bytes have been written to " + filesDir + fileName + ".jpg");
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am not sure, but I think you are taking only one of the plane of the YUV_420_888 format (luminance part).
In my case, I usually transform my image to byte[] in this way.
Image m_img;
Log.v(LOG_TAG,"Format -> "+m_img.getFormat());
Image.Plane Y = m_img.getPlanes()[0];
Image.Plane U = m_img.getPlanes()[1];
Image.Plane V = m_img.getPlanes()[2];
int Yb = Y.getBuffer().remaining();
int Ub = U.getBuffer().remaining();
int Vb = V.getBuffer().remaining();
data = new byte[Yb + Ub + Vb];
//your data length should be this byte array length.
Y.getBuffer().get(data, 0, Yb);
U.getBuffer().get(data, Yb, Ub);
V.getBuffer().get(data, Yb+ Ub, Vb);
final int width = m_img.getWidth();
final int height = m_img.getHeight();
And I use this byte buffer to transform to rgb.
Hope this helps.
Cheers.
Unai.
Your code is requesting JPEG-format images, which are compressed. They'll change in size for every frame, and they'll be much smaller than the uncompressed image. If you want to do nothing besides save JPEG images, you can just save what you have in the byte[] data to disk and you're done.
If you want to actually do something with the JPEG, you can use BitmapFactory.decodeByteArray() to convert it to a Bitmap, for example, though that's pretty inefficient.
Or you can switch to YUV, which is more efficient, but you need to do more work to get a Bitmap out of it.
I'm trying to write a method that accepts an image(Bitmap) and returns a byte[] array. finally, I try to write this byte[] array to a folder so I can see the difference, but my byte[] arraycan not displayed, and in addition, it is not scaled down! This is my method:
private byte[] changeSize(Bitmap image) {
byte[] picture;
int width = image.getWidth();
int height = image.getHeight();
int newHeight = 0, newWidth = 0;
if (width > 250 || height > 250) {
if (width > height) { //landscape-mode
newHeight = 200;
newWidth = (newHeight * width) / height;
} else { //portrait-mode
newWidth = 200;
newHeight = (newWidth * height) / width;
}
} else {
Toast.makeText(this, "Something wrong!", Toast.LENGTH_LONG).show();
}
Bitmap sizeChanged = Bitmap.createScaledBitmap(image, newWidth, newHeight, true);
//Convert bitmap to a byte array
int bytes = sizeChanged.getByteCount();
ByteBuffer bb = ByteBuffer.allocate(bytes);
sizeChanged.copyPixelsFromBuffer(bb);
picture = bb.array();
//Write to a hd
picturePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String fileName = edFile.getText().toString() + "_downscaled" + ".jpg";
File file = new File(picturePath, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(picture);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
I tried several hours to get my byte[] array visible, but I could simply not do this. Any help or hints to show me where I derail is/are very appreciated.
This was working for me
public static Bitmap byteArraytoBitmap(byte[] bytes) {
return (BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
}
public static byte[] bitmaptoByteArray(Bitmap bmp) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); //PNG format is lossless and will ignore the quality setting!
byte[] byteArray = stream.toByteArray();
return byteArray;
}
public static Bitmap bitmapFromFile(File file) {
//returns null if could not decode
return BitmapFactory.decodeFile(file.getPath());
}
public static boolean saveImage(Bitmap image, String filePath) {
LogInfo(TAG, "Saving image to: " + filePath);
File file = new File(filePath);
File fileDirectory = new File(file.getParent());
LogInfo(TAG, fileDirectory.getPath());
if (!fileDirectory.exists()) {
if (!fileDirectory.mkdirs()) {
Log.e(TAG, "ERROR CREATING DIRECTORIES");
return false;
}
}
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bitmaptoByteArray(image));
fo.flush();
fo.close();
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
Hello here is the code:
URL uri = new URL(photoUrl);
URLConnection connection = uri.openConnection();
Log.i(TAG, "connecting...");
connection.connect();
Log.i(TAG, "connected");
Log.i(TAG, "building Bitmap...");
InputStream is = connection.getInputStream();
//BufferedInputStream bis = new BufferedInputStream(is, 8 * 1024);
File myfile = new File(getApplicationContext().getCacheDir(), "wallpaper.tmp");
myfile.createNewFile();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(myfile));
byte buf[]=new byte[1024];
int len;
while((len=is.read(buf))>0)
out.write(buf,0,len);
out.close();
is.close();
Bitmap bmp = BitmapFactory.decodeFile(myfile.getPath());
//Bitmap bmp = BitmapFactory.decodeStream(bis);
Log.i(TAG, "builded Bitmap");
Log.i(TAG, "showing bitmap...");
//int scale;
Matrix matrix = new Matrix();
matrix.setScale(0.1F, 0.1F);
//if (bmp.getWidth() < bmp.getHeight()){
// scale = canvas.getWidth()/bmp.getWidth();
//}else{
// scale = canvas.getHeight()/bmp.getHeight();
//}
//matrix.postScale(scale, scale, bmp.getWidth(), bmp.getHeight());
//matrix.postScale(0.5F, canvas.getWidth()/bmp.getWidth());
//Bitmap bmp2 = Bitmap.createScaledBitmap(bmp, canvas.getWidth(), canvas.getHeight(), true);
//Paint p = new Paint();
//p.setFilterBitmap(true);
//try{
canvas.drawBitmap(bmp, matrix, null);
//}catch(NullPointerException exc){
// //why do we get this??
// Log.d(TAG, "NullPointerException drawing canvas. why?");
// return;
//}
Now what happens is that drawBitmap is blocking since 5 minutes...
Any ideas?
You might get better performance by creating a scaled bitmap in the first place.
Bitmap bmp = BitmapFactory.decodeFile(myfile.getPath());
bmp = bmp.createScaledBitmap(bmp, width, height, true);
Then you won't have to use a matrix when drawing it out to the screen either.
I'm having a problem, when I save my image I can't open it because it's empty and the size is zero kb. I'm reading the image from a folder and then I change the size to 100x100 and save it but it's not working. Here's the code I've written so far:
public BufferedImage resizeImageToPreview() {
final String SOURCE ="/Library/glassfishv3/glassfishv3/glassfish/domains/domain1/eclipseApps/LaFamilyEar/LaFamily_war/temp";
File source = new File(SOURCE);
BufferedImage image = null;
//Read images and convert them to BufferedImages
for (File img : source.listFiles()) {
try {
image = ImageIO.read(img);
} catch (IOException e) {
e.printStackTrace();
}
//Get image width and height
int w = image.getWidth();
int h = image.getHeight();
//Change the width and height to the image to 100x100
// BufferedImage dimg = new BufferedImage(100, 100, image.getType());
//Create graphics to be able to paint or change your image
Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(image, 0, 0, 100, 100, 0, 0, w, h, null);
g.dispose();
String extension = ".jpg";
File dest = new File("/Users/ernestodelgado/Kurs_Java/EjbWorkspace/LaFamily/WebContent/small/"+img.getName());
try {
ImageIO.write(image, extension, dest);
} catch (IOException e) {
e.printStackTrace();
}
}
return image;
}
Try changing ..
String extension = ".jpg";
..to..
String extension = "jpg";
Obviously, add a "." to the file name at the relevant point.
If that does not work for you, try posting an SSCCE.
Try this example:
public class MakeSmaller {
public static void main(String... args) throws MalformedURLException,
IOException {
String url = "http://actionstalk.com/wp-content/uploads/2007/11/google_logo_3600x1500.jpg";
BufferedImage orig = ImageIO.read(new URL(url));
BufferedImage scaled = new BufferedImage(50, 50, orig.getType());
Graphics2D g = (Graphics2D) scaled.getGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(orig, 0, 0, scaled.getWidth(), scaled.getHeight(), null);
g.dispose();
ImageIO.write(scaled, "jpg", new File("test.jpg"));
}
}