-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
627 lines (553 loc) · 20.9 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
<!-- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Capture Photo</title>
<style>
/* Video display and styling */
#video {
width: 100%;
height: auto;
object-fit: cover;
border: 2px solid #ccc;
}
#capture {
display: block;
margin: 20px auto;
padding: 10px 20px;
background-color: #007BFF;
color: white;
border: none;
font-size: 16px;
cursor: pointer;
}
#capture:hover {
background-color: #0056b3;
}
#capturedImage {
max-width: 100%;
margin-top: 20px;
display: none;
}
#recapture {
display: none;
padding: 10px 20px;
background-color: #28a745;
color: white;
border: none;
font-size: 16px;
cursor: pointer;
}
#recapture:hover {
background-color: #218838;
}
.container {
text-align: center;
max-width: 600px;
margin: 0 auto;
}
body {
font-family: Arial, sans-serif;
padding: 20px;
background-color: #f4f4f9;
}
</style>
</head>
<body>
<h1>Capture Photo</h1>
<div class="container">
<video id="video" autoplay muted playsinline></video>
<button id="capture">Capture</button>
<button id="swapCamera">Swap Camera</button>
<canvas id="canvas" style="display:none;"></canvas>
<img id="capturedImage" />
<button id="recapture">Re-capture</button>
</div>
<script>
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const captureButton = document.getElementById('capture');
const swapCameraButton = document.getElementById('swapCamera');
const capturedImage = document.getElementById('capturedImage');
const recaptureButton = document.getElementById('recapture');
let currentStream;
let currentDeviceId = null;
let videoWidth = 640; // Default video resolution
let videoHeight = 480;
// Function to start the video stream with higher resolution
function startVideoStream(deviceId = null) {
const constraints = {
video: {
deviceId: deviceId ? { exact: deviceId } : undefined,
width: { ideal: 1920 }, // Request a higher resolution
height: { ideal: 1080 }, // Request a higher resolution
}
};
// Stop current stream if exists
if (currentStream) {
const tracks = currentStream.getTracks();
tracks.forEach(track => track.stop());
}
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
console.log('Camera stream started');
currentStream = stream;
video.srcObject = stream;
// Ensure video starts playing once metadata is loaded
video.onloadedmetadata = function () {
console.log('Video metadata loaded, starting video playback');
video.play();
videoWidth = video.videoWidth;
videoHeight = video.videoHeight;
// Set canvas size to match video size
canvas.width = videoWidth;
canvas.height = videoHeight;
};
video.onerror = function (error) {
console.error('Video stream error: ', error);
alert('Error with video stream: ' + error.message);
};
})
.catch(error => {
console.error('Error accessing camera: ', error);
alert('Error accessing camera: ' + error.message);
});
}
// Function to get the list of available video devices (front/back cameras)
function getVideoDevices() {
return navigator.mediaDevices.enumerateDevices()
.then(devices => {
const videoDevices = devices.filter(device => device.kind === 'videoinput');
return videoDevices;
})
.catch(err => {
console.error('Error enumerating devices: ', err);
alert('Error enumerating devices: ' + err.message);
});
}
// Start video with default camera (usually front-facing)
getVideoDevices().then(videoDevices => {
if (videoDevices.length === 0) {
alert('No video devices found.');
return;
}
// Get the first video device (typically the front camera)
currentDeviceId = videoDevices[0].deviceId;
startVideoStream(currentDeviceId);
});
// Button to capture the image
captureButton.addEventListener('click', () => {
if (video.srcObject) {
// Ensure the canvas matches the resolution of the video stream
canvas.width = videoWidth;
canvas.height = videoHeight;
context.drawImage(video, 0, 0, canvas.width, canvas.height);
// Convert to PNG image with high quality
const imageData = canvas.toDataURL('image/png', 1.0); // High quality
capturedImage.src = imageData;
capturedImage.style.display = 'block';
video.style.display = 'none';
captureButton.style.display = 'none';
recaptureButton.style.display = 'inline-block'; // Show the recapture button
} else {
alert('Video stream is not available.');
}
});
// Button to swap the camera
swapCameraButton.addEventListener('click', () => {
getVideoDevices().then(videoDevices => {
if (videoDevices.length < 2) {
alert('No additional camera available.');
return;
}
// Prevent fullscreen on iOS Safari/Chrome
exitFullscreen();
// Find the other camera (swap between the first and second device)
const nextDeviceId = videoDevices.find(device => device.deviceId !== currentDeviceId).deviceId;
currentDeviceId = nextDeviceId;
// Restart the stream with the new camera
startVideoStream(currentDeviceId);
});
});
// Exit fullscreen if the browser has triggered it (for iOS Safari/Chrome)
function exitFullscreen() {
if (document.fullscreenElement || document.webkitFullscreenElement) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
}
// Prevent fullscreen on touch events for iOS Safari/Chrome
function preventFullscreen(event) {
if (event.target === video) {
event.preventDefault(); // Prevent fullscreen
}
}
// Attach listeners to prevent fullscreen
video.addEventListener('touchstart', preventFullscreen, { passive: false });
video.addEventListener('click', preventFullscreen, { passive: false });
// Ensure the video keeps playing after exiting fullscreen
video.onfullscreenchange = function () {
if (!document.fullscreenElement && !document.webkitFullscreenElement) {
video.play();
}
};
// Button to re-capture the image
recaptureButton.addEventListener('click', () => {
capturedImage.style.display = 'none';
captureButton.style.display = 'inline-block';
recaptureButton.style.display = 'none';
video.style.display = 'block';
});
</script>
</body>
</html>
-->
<!-- CAN AUTO UPLOAD GOOGLE ACC THAT I LOGIN TO
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Capture and Upload Photo to Google Drive</title>
<style>
/* Styles here */
#video, #capturedImage {
width: 100%;
max-width: 600px;
margin: 10px auto;
display: block;
border: 1px solid #ccc;
}
#controls {
text-align: center;
margin: 20px;
}
button {
padding: 10px 20px;
font-size: 16px;
margin: 5px;
}
</style>
</head>
<body>
<h1>Capture and Upload Photo to Google Drive</h1>
<div id="controls">
<video id="video" autoplay playsinline></video>
<button id="capture">Capture</button>
<button id="swapCamera">Swap Camera</button>
<canvas id="canvas" style="display:none;"></canvas>
<img id="capturedImage" style="display:none;" />
<button id="recapture" style="display:none;">Re-capture</button>
<button id="authButton" onclick="handleAuthClick()">Sign In with Google</button>
</div>
// Include GIS client library
<script src="https://accounts.google.com/gsi/client" async defer></script>
<script src="https://apis.google.com/js/api.js"></script>
<script>
const CLIENT_ID = '236823481359-hec318cfi6l4dlori28m4o71b6q46ka7.apps.googleusercontent.com';
const API_KEY = 'AIzaSyA0tbk_qHuSg1PfZEEw_kAftrrgUVdOBpY';
const SCOPES = 'https://www.googleapis.com/auth/drive.file';
let currentStream = null;
let currentDeviceId = null;
let tokenClient;
let videoWidth = 640;
let videoHeight = 480;
// Initialize Google API client for Drive access
function initGoogleAPI() {
gapi.load('client', () => {
gapi.client.init({
apiKey: API_KEY,
discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
}).then(() => {
console.log("Google API client loaded successfully.");
}).catch(error => {
console.error("Error initializing Google API client", error);
});
});
}
// Initialize the token client for OAuth
function initTokenClient() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: (tokenResponse) => {
console.log('Token acquired:', tokenResponse);
},
});
}
function handleAuthClick() {
tokenClient.requestAccessToken({ prompt: '' });
}
function startVideoStream(deviceId = null) {
const constraints = {
video: {
deviceId: deviceId ? { exact: deviceId } : undefined,
width: { ideal: 1920 },
height: { ideal: 1080 },
}
};
// Stop previous video stream if any
if (currentStream) {
currentStream.getTracks().forEach(track => track.stop());
}
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
currentStream = stream;
document.getElementById('video').srcObject = stream;
document.getElementById('video').onloadedmetadata = function() {
videoWidth = this.videoWidth;
videoHeight = this.videoHeight;
this.play();
};
})
.catch(error => {
console.error('Error accessing camera:', error);
alert('Error accessing camera: ' + error.message);
});
}
function swapCamera() {
navigator.mediaDevices.enumerateDevices()
.then(devices => {
const videoDevices = devices.filter(device => device.kind === 'videoinput');
if (videoDevices.length < 2) {
alert('No additional camera available.');
return;
}
// Toggle between available cameras
const nextDevice = videoDevices.find(device => device.deviceId !== currentDeviceId);
currentDeviceId = nextDevice.deviceId;
startVideoStream(currentDeviceId);
})
.catch(error => {
console.error('Error enumerating devices:', error);
});
}
function captureImage() {
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
canvas.width = videoWidth;
canvas.height = videoHeight;
context.drawImage(document.getElementById('video'), 0, 0, canvas.width, canvas.height);
const imageData = canvas.toDataURL('image/png');
document.getElementById('capturedImage').src = imageData;
document.getElementById('capturedImage').style.display = 'block';
document.getElementById('video').style.display = 'none';
document.getElementById('capture').style.display = 'none';
document.getElementById('recapture').style.display = 'inline-block';
uploadToGoogleDrive(imageData);
}
function uploadToGoogleDrive(imageData) {
if (!gapi.client) {
console.log('Google API client not initialized');
alert('Please wait until Google API is initialized');
return;
}
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const closeDelimiter = "\r\n--" + boundary + "--";
const metadata = {
'name': 'captured_image.png',
'mimeType': 'image/png'
};
const base64Data = imageData.split(',')[1];
const multipartRequestBody =
delimiter +
'Content-Type: application/json; charset=UTF-8\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: image/png\r\n' +
'Content-Transfer-Encoding: base64\r\n\r\n' +
base64Data +
closeDelimiter;
gapi.client.request({
'path': '/upload/drive/v3/files?uploadType=multipart',
'method': 'POST',
'headers': {
'Authorization': `Bearer ${gapi.auth.getToken().access_token}`,
'Content-Type': `multipart/related; boundary="${boundary}"`,
},
'body': multipartRequestBody
}).then(response => {
console.log('File uploaded successfully', response);
alert('Image uploaded to Google Drive!');
}).catch(error => {
console.error('Error uploading file', error);
});
}
document.getElementById('capture').addEventListener('click', captureImage);
document.getElementById('swapCamera').addEventListener('click', swapCamera);
document.getElementById('recapture').addEventListener('click', () => {
document.getElementById('capturedImage').style.display = 'none';
document.getElementById('capture').style.display = 'inline-block';
document.getElementById('recapture').style.display = 'none';
document.getElementById('video').style.display = 'block';
});
window.onload = function() {
initGoogleAPI();
initTokenClient();
navigator.mediaDevices.enumerateDevices().then(devices => {
const videoDevices = devices.filter(device => device.kind === 'videoinput');
if (videoDevices.length > 0) {
currentDeviceId = videoDevices[0].deviceId;
startVideoStream(currentDeviceId);
} else {
alert('No video devices found.');
}
});
};
</script>
</body>
</html>
CAN AUTO UPLOAD GOOGLE ACC THAT I LOGIN TO-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Capture and Upload Photo to Centralized Imgur Account</title>
<style>
/* Your existing styles */
</style>
</head>
<body>
<h1>Capture and Upload Photo to Centralized Imgur Account</h1>
<div class="container">
<video id="video" autoplay muted playsinline></video>
<button id="capture">Capture</button>
<button id="swapCamera">Swap Camera</button>
<canvas id="canvas" style="display:none;"></canvas>
<img id="capturedImage" />
<button id="recapture">Re-capture</button>
</div>
<script>
// Imgur client ID and OAuth URLs
const CLIENT_ID = '80cfe0d2cc13ec4'; // Replace with your Imgur Client ID
const CLIENT_SECRET = '62f9e7a3edceea3f2df1e936ad32d5bd2b6e97e7'; // Replace with your Imgur Client Secret
const OAUTH_URL = 'https://api.imgur.com/oauth2/authorize';
const TOKEN_URL = 'https://api.imgur.com/oauth2/token';
const SCOPES = 'account'; // Required scope to upload images to the account
let accessToken = null;
let currentStream;
let videoWidth = 640;
let videoHeight = 480;
// Step 1: Redirect user to Imgur to authenticate and authorize the app
function redirectToImgurAuth() {
const redirectUri = encodeURIComponent('https://crystalfied.github.io'); // Update with your callback URL
const authUrl = `${OAUTH_URL}?client_id=${CLIENT_ID}&response_type=code&state=123&scope=${SCOPES}&redirect_uri=${redirectUri}`;
window.location.href = authUrl;
}
// Step 2: Handle the OAuth callback and exchange code for access token
function getAccessTokenFromCode(code) {
const data = new URLSearchParams();
data.append('client_id', CLIENT_ID);
data.append('client_secret', CLIENT_SECRET);
data.append('code', code);
data.append('grant_type', 'authorization_code');
data.append('redirect_uri', 'https://crystalfied.github.io'); // Same as the callback URL
fetch(TOKEN_URL, {
method: 'POST',
body: data
})
.then(response => response.json())
.then(data => {
accessToken = data.access_token;
console.log('Access token received:', accessToken);
alert('Authentication successful!');
})
.catch(error => {
console.error('Error exchanging code for token:', error);
alert('Failed to authenticate.');
});
}
// Step 3: Upload image to the centralized Imgur account
function uploadToImgur(imageData) {
if (!accessToken) {
alert('You need to authenticate first!');
return;
}
fetch('https://api.imgur.com/3/upload', {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
},
body: new FormData().append('image', imageData)
})
.then(response => response.json())
.then(data => {
console.log('Image uploaded successfully:', data);
alert('Image uploaded to the centralized Imgur account!');
})
.catch(error => {
console.error('Error uploading image:', error);
alert('Failed to upload image.');
});
}
// Capture image from video
document.getElementById('capture').addEventListener('click', () => {
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
canvas.width = videoWidth;
canvas.height = videoHeight;
context.drawImage(document.getElementById('video'), 0, 0, canvas.width, canvas.height);
// Convert to Blob (form data for uploading)
canvas.toBlob(blob => {
uploadToImgur(blob); // Pass the Blob to upload function
}, 'image/png');
// Display the captured image
const imageData = canvas.toDataURL('image/png');
document.getElementById('capturedImage').src = imageData;
document.getElementById('capturedImage').style.display = 'block';
document.getElementById('video').style.display = 'none';
document.getElementById('capture').style.display = 'none';
document.getElementById('recapture').style.display = 'inline-block';
});
// Handle Re-capture
document.getElementById('recapture').addEventListener('click', () => {
document.getElementById('capturedImage').style.display = 'none';
document.getElementById('capture').style.display = 'inline-block';
document.getElementById('recapture').style.display = 'none';
document.getElementById('video').style.display = 'block';
});
// Start the video stream
function startVideoStream() {
const constraints = { video: { width: 1920, height: 1080 } };
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
currentStream = stream;
document.getElementById('video').srcObject = stream;
})
.catch(error => {
console.error('Error accessing camera: ', error);
alert('Error accessing camera: ' + error.message);
});
}
// Swap camera functionality (front/back)
document.getElementById('swapCamera').addEventListener('click', () => {
navigator.mediaDevices.enumerateDevices().then(devices => {
const videoDevices = devices.filter(device => device.kind === 'videoinput');
const nextDeviceId = videoDevices[1]?.deviceId || videoDevices[0]?.deviceId;
startVideoStream(nextDeviceId);
});
});
// Initialize video stream on page load
window.onload = function() {
startVideoStream();
// Check if there's an authorization code in the URL
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
// If there's an authorization code, exchange it for an access token
if (code) {
getAccessTokenFromCode(code);
} else {
// If no access token is found, prompt for authentication
redirectToImgurAuth();
}
};
</script>
</body>
</html>