I'm trying convert sequantial images to video file.
But, this source makes error in encoding video.
public class Image2Video {
private static final double FRAME_RATE = 20;
private static final int SECONDS_TO_RUN_FOR = 20;
private static final String outputFilename = "C:/image/myVideo.mp4";
private static Dimension screenBounds;
private static Map<String, File> imageMap = new HashMap<String, File>();
public static void main(String[] args) {
final IMediaWriter writer = ToolFactory.makeWriter(outputFilename);
screenBounds = Toolkit.getDefaultToolkit().getScreenSize();
writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_MPEG4,screenBounds.width / 2, screenBounds.height / 2);
File folder = new File("C:/image");
File[] listOfFiles = folder.listFiles();
int indexVal = 0;
for (File file : listOfFiles) {
if (file.isFile()) {
indexVal++;
System.out.println("file.getName() :"+file.getName());
imageMap.put(file.getName(), file);
}
}
for (int index = 1; index <= listOfFiles.length; index++) {
BufferedImage screen = getImage(index);
BufferedImage bgrScreen = convertToType(screen, BufferedImage.TYPE_3BYTE_BGR);
writer.encodeVideo(0, bgrScreen, 300*index, TimeUnit.MILLISECONDS);
}
writer.close();
System.out.println("Video Created");
}
public static BufferedImage convertToType(BufferedImage sourceImage, int targetType) {
BufferedImage image;
if (sourceImage.getType() == targetType) {
image = sourceImage;
}
else {
image = new BufferedImage(sourceImage.getWidth(),
sourceImage.getHeight(), targetType);
image.getGraphics().drawImage(sourceImage, 0, 0, null);
}
return image;
}
private static BufferedImage getImage(int index) {
try {
String fileName=index+".jpeg";
System.out.println("fileName :" + fileName);
File img = imageMap.get(fileName);
BufferedImage in=null;
if (img != null) {
System.out.println("img :"+img.getName());
in = ImageIO.read(img);
}else
{
System.out.println("++++++++++++++++++++++++++++++++++++++index :" + index);
img = imageMap.get(1);
in = ImageIO.read(img);
}
return in;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
This is happening becz your images are not of the exact same width, height.
Try to run the program with images of similar dimensions, you can see that the problem goes away.
You could convert your images to same width/height before feeding them to this program.
Related
this must be a stupid question but please help me. How can we get the image file path in camera2basic api and display the image on the other activity's imageview? I have been trying to get the "Absolutepath" of the mFile in the project but not getting anything.
As Camera2 api is relatively complex to understand for me. Please help me.
public override void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
mFile = new Java.IO.File(Activity.GetExternalFilesDir(null), "pic.jpg");
mCaptureCallback = new CameraCaptureListener(this);
mOnImageAvailableListener = new ImageAvailableListener(this, mFile);
}
when we press the button, it evokes takepicture(); which has lockfocus();
private void LockFocus()
{
try
{
// This is how to tell the camera to lock focus.
mPreviewRequestBuilder.Set(CaptureRequest.ControlAfTrigger, (int)ControlAFTrigger.Start);
// Tell #mCaptureCallback to wait for the lock.
mState = STATE_WAITING_LOCK;
mCaptureSession.Capture(mPreviewRequestBuilder.Build(), mCaptureCallback,
mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
I have showCapturePhoto which is getting the image from ImageAvailableListener
using Android.Media;
using Java.IO;
using Java.Lang;
using Java.Nio;
using Android.Util;
namespace Camera2Basic.Listeners
{
public class ImageAvailableListener : Java.Lang.Object,
ImageReader.IOnImageAvailableListener
{
private readonly File file;
private Camera2BasicFragment owner;
public ImageAvailableListener(Camera2BasicFragment fragment, File
file)
{
if (fragment == null)
throw new System.ArgumentNullException("fragment");
if (file == null)
throw new System.ArgumentNullException("file");
owner = fragment;
this.file = file;
}
//public File File { get; private set; }
//public Camera2BasicFragment Owner { get; private set; }
public void OnImageAvailable(ImageReader reader)
{
owner.mBackgroundHandler.Post(new ImageSaver(reader.AcquireNextImage(), file));
}
// Saves a JPEG {#link Image} into the specified {#link File}.
private class ImageSaver : Java.Lang.Object, IRunnable
{
// The JPEG image
private Image mImage;
// The file we save the image into.
private File mFile;
public ImageSaver(Image image, File file)
{
if (image == null)
throw new System.ArgumentNullException("image");
if (file == null)
throw new System.ArgumentNullException("file");
mImage = image;
mFile = file;
}
public void Run()
{
ByteBuffer buffer = mImage.GetPlanes()[0].Buffer;
byte[] bytes = new byte[buffer.Remaining()];
buffer.Get(bytes);
using (var output = new FileOutputStream(mFile))
{
try
{
output.Write(bytes);
}
catch (IOException e)
{
e.PrintStackTrace();
}
finally
{
mImage.Close();
}
}
Camera2BasicFragment.showCapturedPhoto(mImage);
}
}
}
}
ShowcapturePhoto
public static void showCapturedPhoto(Image img)
{
ByteBuffer buffer;
byte[] bytes;
MemoryStream memStream = new MemoryStream();
buffer = img.GetPlanes()[0].Buffer;
bytes = new byte[buffer.Capacity()];
buffer.Get(bytes);
Activity activity= new Activity();
Intent showPhoto = new Intent(activity, typeof(RetryOK));
showPhoto.PutExtra("savedImg", bytes);
showPhoto.PutExtra("zoomAmount", 1.7f / 1.4f);
showPhoto.PutExtra("focusDistance", -1.0f);
activity.StartActivity(typeof(RetryOK));
}
I have been following this tutorial to learn how to implement Pinch Zoom and Pan capabilities into an app I am developing.
https://www.youtube.com/watch?v=BY8hLhu50po&list=PL9jCwTXYWjDJjDE_JxRozYGKGt8gbUXg7
Basically, he loads an image from the gallery and displays it in an image view that supports Zoom/Pan functionality.
I would like to preload an image into the image view rather than select one from the gallery. Ideally, I'd like to load an image from drawable.
The tutorial's app had a lot of extra features that I am trying to weed out.
First it opens a gallery. Then you select an image to display, and it displays it as a thumbnail inside of mImageView.
On Long Click, it hides mImageView and displays a maximized image inside of a second Image View. (MPinchZoomImageView)
At this point, the image supports zoom and pan functionality.
If I could, I'd like to skip the gallery and the first Image View and only use the PinchZoom Image View. I'm not sure how I'd do that.
Code:
ImageViewMainActivity
public class ImageViewMainActivity extends AppCompatActivity {
ImageView mImageView;
PinchZoomImageView mPinchZoomImageView;
private Uri mImageUri;
private static final int REQUEST_OPEN_RESULT_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_view_main);
mImageView = (ImageView) findViewById(R.id.imageView);
mPinchZoomImageView = (PinchZoomImageView) findViewById(R.id.pinchZoomImageView);
mImageView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
pinchZoomPan();
return true;
}
});
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_OPEN_RESULT_CODE); // pass it a context of 0
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
View decorView = getWindow().getDecorView();
if(hasFocus) {
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if(requestCode == REQUEST_OPEN_RESULT_CODE && resultCode == RESULT_OK) {
if(resultData != null) {
mImageUri = resultData.getData();
Glide.with(this)
.load(mImageUri)
.into(mImageView);
}
}
}
private void pinchZoomPan() {
mPinchZoomImageView.setImageUri(mImageUri);
mImageView.setAlpha(0.f); // set mImageView invisible.
mPinchZoomImageView.setVisibility(View.VISIBLE);
}
}
PinchZoomImageView
public class PinchZoomImageView extends ImageView {
private Bitmap mBitmap;
private int mImageWidth;
private int mImageHeight;
private final static float mMinZoom = 1.f;
private final static float mMaxZoom = 4.f;
private float mScaleFactor = 1.f;
private ScaleGestureDetector mScaleGestureDetector;
private final static int NONE = 0;
private final static int PAN = 1;
private final static int ZOOM = 2;
private int mEventState;
private float mStartX = 0;
private float mStartY = 0;
private float mTranslateX = 0;
private float mTranslateY = 0;
private float mPreviousTranslateX = 0;
private float mPreviousTranslateY = 0;
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
mScaleFactor = Math.max(mMinZoom, Math.min(mMaxZoom, mScaleFactor));
// invalidate();
// requestLayout();
return super.onScale(detector);
}
}
public PinchZoomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
mScaleGestureDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mEventState = PAN;
mStartX = event.getX() - mPreviousTranslateX;
mStartY = event.getY() - mPreviousTranslateY;
break;
case MotionEvent.ACTION_UP:
mEventState = NONE;
mPreviousTranslateX = mTranslateX;
mPreviousTranslateY = mTranslateY;
break;
case MotionEvent.ACTION_MOVE:
mTranslateX = event.getX() - mStartX;
mTranslateY = event.getY() - mStartY;
break;
case MotionEvent.ACTION_POINTER_DOWN:
mEventState = ZOOM;
break;
}
mScaleGestureDetector.onTouchEvent(event);
if((mEventState == PAN && mScaleFactor != mMinZoom) || mEventState == ZOOM) { // called under the condition that window is zoomed i
invalidate();
requestLayout();
}
return true;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int imageWidth = MeasureSpec.getSize(widthMeasureSpec);
int imageHeight = MeasureSpec.getSize(heightMeasureSpec);
int scaledWidth = Math.round(mImageWidth * mScaleFactor);
int scaledHeight = Math.round(mImageHeight * mScaleFactor);
setMeasuredDimension(
Math.min(imageWidth, scaledWidth),
Math.min(imageHeight, scaledHeight)
);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.scale(mScaleFactor, mScaleFactor);
// canvas.scale(mScaleFactor, mScaleFactor, mScaleGestureDetector.getFocusX(), mScaleGestureDetector.getFocusY());
if((mTranslateX * -1) < 0) {
mTranslateX = 0;
} else if ((mTranslateX * -1) > mImageWidth * mScaleFactor - getWidth()) {
mTranslateX = (mImageWidth * mScaleFactor - getWidth()) * -1;
}
if((mTranslateY * -1) < 0) {
mTranslateY = 0;
} else if ((mTranslateY * -1) > mImageHeight * mScaleFactor - getHeight()) {
mTranslateY = (mImageHeight * mScaleFactor - getHeight()) * -1;
}
canvas.translate(mTranslateX/mScaleFactor, mTranslateY/mScaleFactor);
canvas.drawBitmap(mBitmap, 0, 0, null);
canvas.restore();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
public void setImageUri(Uri uri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri);
float aspecRatio = (float) bitmap.getHeight() / (float) bitmap.getWidth();
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
mImageWidth = displayMetrics.widthPixels;
mImageHeight = Math.round(mImageWidth * aspecRatio);
mBitmap = Bitmap.createScaledBitmap(bitmap, mImageWidth, mImageHeight, false);
invalidate();
requestLayout();
} catch (IOException e) {
e.printStackTrace();
}
}
}
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mobapptut.com.imageviewer.ImageViewMainActivity">
<ImageView
android:layout_width="200dp"
android:layout_height="150dp"
android:id="#+id/imageView"
android:layout_centerInParent="true" />
<mobapptut.com.imageviewer.PinchZoomImageView
android:visibility="invisible"
android:id="#+id/pinchZoomImageView"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Thank You
i use VLCJ 3.0.1, Plattform 3.5.2 and JNA 3.5.2 under Ubuntu 14.10.
I would like to create a simple Vlcj Mediaplayer with equalizer.
The problem is, i can play the *.mp3, but when i enable the equalizer and change the gain from any band, i can hear that gain from the band up to max high. I couldn't change it to lower gain. No effect from the Slider. Only when i change the gain to max or min, the effekt is off.
Here is the Code only for testing:
FesterTest.java
public static void main(String[] args) {
Canvas m_surface;
EmbeddedMediaPlayer m_mediaPlayer;
Equalizer m_equalizer;
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
m_surface = new Canvas();
m_surface.setBackground(Color.black);
m_surface.setBounds(0, 0, 1024, 600);
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
m_mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
m_mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(m_surface));
System.out.println(mediaPlayerFactory.isEqualizerAvailable());
m_equalizer = mediaPlayerFactory.newEqualizer();
System.out.println(LibVlcConst.MAX_GAIN);
System.out.println(LibVlcConst.MIN_GAIN);
System.out.println(LibVlcConst.MIN_VOLUME);
System.out.println(LibVlcConst.MAX_VOLUME);
JFrame f = new JFrame();
JPanel p = new JPanel();
f.add(p);
p.add(m_surface);
f.setVisible(true);
m_mediaPlayer.playMedia("/home/patrick/Dev/content/068-becky_g_-_shower.mp3");
EqualizerFrame frame = new EqualizerFrame(mediaPlayerFactory.getEqualizerBandFrequencies(), mediaPlayerFactory.getEqualizerPresetNames(), mediaPlayerFactory, m_mediaPlayer, m_equalizer);
frame.pack();
frame.setVisible(true);
}
and EqualizerFrame:
public class EqualizerFrame extends JFrame implements ChangeListener, ActionListener, ItemListener {
private static final String BAND_INDEX_PROPERTY = "equalizerBandIndex";
private final String dbFormat = "%.2fdB";
private final MediaPlayerFactory mediaPlayerFactory;
private final MediaPlayer mediaPlayer;
private final Equalizer equalizer;
private final SliderControl preampControl;
private final SliderControl[] bandControls;
private final JToggleButton enableButton;
private final JComboBox presetComboBox;
#SuppressWarnings({ "unchecked", "rawtypes" })
public EqualizerFrame(List<Float> list, List<String> presets, MediaPlayerFactory mediaPlayerFactory, MediaPlayer mediaPlayer, Equalizer equalizer) {
super("Equalizer");
this.mediaPlayerFactory = mediaPlayerFactory;
this.mediaPlayer = mediaPlayer;
this.equalizer = equalizer;
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
contentPane.setLayout(new BorderLayout(0, 4));
JPanel bandsPane = new JPanel();
bandsPane.setLayout(new GridLayout(1, 1 + list.size(), 2, 0));
preampControl = new SliderControl("Preamp", (int)LibVlcConst.MIN_GAIN, (int)LibVlcConst.MAX_GAIN, 0, dbFormat);
preampControl.getSlider().addChangeListener(this);
bandsPane.add(preampControl);
bandControls = new SliderControl[list.size()];
for(int i = 0; i < list.size(); i++) {
bandControls[i] = new SliderControl(formatFrequency(list.get(i)), (int)LibVlcConst.MIN_GAIN, (int)LibVlcConst.MAX_GAIN, 0, dbFormat);
bandControls[i].getSlider().putClientProperty(BAND_INDEX_PROPERTY, i);
bandControls[i].getSlider().addChangeListener(this);
bandsPane.add(bandControls[i]);
}
contentPane.add(bandsPane, BorderLayout.CENTER);
JPanel controlsPane = new JPanel();
controlsPane.setLayout(new BoxLayout(controlsPane, BoxLayout.X_AXIS));
enableButton = new JToggleButton("Enable");
enableButton.setMnemonic('e');
controlsPane.add(enableButton);
controlsPane.add(Box.createHorizontalGlue());
JLabel presetLabel = new JLabel("Preset:");
presetLabel.setDisplayedMnemonic('p');
controlsPane.add(presetLabel);
presetComboBox = new JComboBox();
presetLabel.setLabelFor(presetComboBox);
DefaultComboBoxModel presetModel = (DefaultComboBoxModel)presetComboBox.getModel();
presetModel.addElement(null);
for(String presetName : presets) {
presetModel.addElement(presetName);
}
presetComboBox.setRenderer(new DefaultListCellRenderer() {
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel)super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(value != null) {
label.setText(String.valueOf(value));
}
else {
label.setText("--Select--");
}
return label;
}
});
controlsPane.add(presetComboBox);
contentPane.add(controlsPane, BorderLayout.SOUTH);
setContentPane(contentPane);
enableButton.addActionListener(this);
presetComboBox.addItemListener(this);
}
private String formatFrequency(float hz) {
if(hz < 1000.0f) {
return String.format("%.0f Hz", hz);
}
else {
return String.format("%.0f kHz", hz / 1000f);
}
}
#Override
public final void actionPerformed(ActionEvent e) {
boolean enable = enableButton.isSelected();
if(!enable) {
presetComboBox.setSelectedItem(null);
}
mediaPlayer.setEqualizer(enable ? equalizer : null);
}
#Override
public void stateChanged(ChangeEvent e) {
if(e.getSource() instanceof JSlider) {
JSlider slider = (JSlider)e.getSource();
Integer index = (Integer)slider.getClientProperty(BAND_INDEX_PROPERTY);
int value = slider.getValue();
// Band...
if(index != null) {
equalizer.setAmp(index, (value / 100f));
}
// Preamp...
else {
equalizer.setPreamp(value / 100f);
}
if(!applyingPreset) {
presetComboBox.setSelectedItem(null);
}
}
}
boolean applyingPreset;
#Override
public final void itemStateChanged(ItemEvent e) {
String presetName = (String)presetComboBox.getSelectedItem();
if(e.getStateChange() == ItemEvent.SELECTED) {
if(presetName != null) {
Equalizer presetEqualizer = mediaPlayerFactory.newEqualizer(presetName);
if(presetEqualizer != null) {
applyingPreset = true;
preampControl.getSlider().setValue((int)(presetEqualizer.getPreamp() * 100f)); // FIXME
float[] amps = presetEqualizer.getAmps();
for(int i = 0; i < amps.length; i++) {
bandControls[i].getSlider().setValue((int)(amps[i] * 100f));
}
applyingPreset = false;
}
}
}
}
}
I don't know what can i do an hope anybody can help me!!!!
Thanks
Patrick
I've revisited this post. I have been able to upload the text file, create a GUI, populate the GUI with JRadioButtons that are labeled from the text file...
Now, I cannot get the background to change color when the JRadioButton is selected! I know that it has something to do with the ActionListener, but how do I fix this? The color needs to be implemented from the hex color code.
public class FP extends JFrame implements ActionListener {
TreeMap<String, String> buttonMap = new TreeMap <>();
// Constructor
#SuppressWarnings("empty-statement")
public FP() throws IOException {
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
panel.setBorder(new TitledBorder("Pick a Radio Button!"));
JRadioButton[] btnArray = new JRadioButton[20];
ButtonGroup btnGroup = new ButtonGroup();
BufferedReader reader;
reader = new BufferedReader(new FileReader("src/colors.txt"));
String currentLine = reader.readLine();
while (currentLine != null) {
String[] pair = currentLine.split("\\s+");
buttonMap.put(pair[0],pair[1]);
currentLine = reader.readLine();
}
//check retrieving values from the buttonMap
for(Map.Entry<String,String> entry : buttonMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
for (int i = 0; i<20; i++){
for(Map.Entry<String, String> entry : buttonMap.entrySet()){
JRadioButton rb = new JRadioButton(entry.getKey() + " " + entry.getValue());
panel.add(rb);
btnGroup.add(rb);
rb.addActionListener(this);
}
}
//private final JRadioButton btnMale = new JRadioButton("Male")
Collection bMapIt = buttonMap.entrySet();
Iterator it = bMapIt.iterator();
System.out.println("Colors and codes");
while(it.hasNext())
System.out.println(it.next());
}
#Override
public void actionPerformed(ActionEvent e) {
setBackground(Color.decode(buttonMap.get(e)));
}
public static void main(String[] args) throws IOException {
FP frame = new FP();
frame.setVisible(true);
frame.setSize(350, 240);
frame.setTitle("Final Project");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
for(Map.Entry<String, String> entry : buttonMap.entrySet()){
for (int i = 0; i<1; i++){
btnArray[i] = new JRadioButton(entry.getKey() + " " + entry.getValue());
panel.add(btnArray[i]);
btnGroup.add(btnArray[i]);
btnArray[i].addActionListener((ActionEvent e) -> {
String btnColor = buttonMap.get(((JRadioButton) e.getSource()).getText());
String hexColor = entry.getValue();
System.out.println(hexColor);
panel.setBackground(Color.decode("#"+hexColor));
});
}
}
This with the addition of class....
#Override
public void actionPerformed(ActionEvent e) {}
}
In My application I am capturing image from camera and storing it in folder created by me. This folder is getting created in Pictures. Now I wants to save same image in my local storages's /BackUp folder.
This is code for
public class MainActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private MultipartEntity multipartEntity;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "FORMS";
private Bitmap bitmap1;
private Uri fileUri; // file url to store image/video
private static String output;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/*
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
private void previewCapturedImage() {
try {
imgPreview.setVisibility(View.VISIBLE);
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap1);
//imgPreview.setImageBitmap(result);
} catch (NullPointerException e) {
e.printStackTrace();
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
}
return mediaFile;
}
Right Now this image is getting save at PICTURES/FORMS Folder. I wants to save it to FORMSBACKUP/IMAGES Folder as well.