I try to show camera preview in SurfaceView and upload that preview to my website. Something like a wireless webcam. Preview is displayed in surfaceView fine but it seem to be cannot upload to my website, i receive nothing in my website. Here is my code in android
public class MainActivity extends AppCompatActivity {
SurfaceView surfaceView;
SurfaceHolder holder;
private Camera camera;
String MyImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
holder = surfaceView.getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
try
{
camera.setPreviewDisplay(holder);
camera.startPreview();
camera.setDisplayOrientation(90);
camera.setPreviewCallback(new Camera.PreviewCallback()
{
public void onPreviewFrame(final byte[] data, final Camera camera)
{
MyImage = Base64.encodeToString(data, Base64.DEFAULT);
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",MyImage));
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://nns12151069.esy.es/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}catch(Exception e){e.printStackTrace();}
}
});
t.start();
}
});
}
catch (IOException e) {e.printStackTrace();}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
}
});
}
}
and .php file which receive preview in website
<?php
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
$path = "publib_html/";
$tmp_name = $_FILES['file']['tmp_name'];
$name = $_FILES['file']['name'];
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
move_uploaded_file($tmp_name,$path.$name);
?>
Preview images are not normally JPEG images, and your server code seems to suggest that you think that they are. The actual format is based on what you supply to setPreviewFormat()
on Camera.Parameters
and has to be one of the values from getSupportedPreviewFormats()
. Most likely you will wind up with NV21
or YV12
.