여행을 떠나며 우리는 수많은 사진을 찍습니다. 그런데 이 사진들 속에는 단순한 이미지 이상의 정보가 담겨 있다는 사실, 알고 계셨나요? 바로 EXIF 데이터입니다. 이 데이터를 활용하면 우리가 방문한 장소와 시간을 추적하고, 더 나아가 주변의 멋진 관광지나 맛집까지 추천받을 수 있습니다.
* 사전 지식 요건 : flask, python, Maps JavaScript API 에서 google map 에 접근 할 수 있는 api 를 발급 해야 합니다.
실습: 사진 GPS 좌표 추출과 위치 정보가 없는 경우
사진 파일에 GPS가 저장되어 있어야 촬영 위치를 좌표로 확인할 수 있습니다. GPS가 없는 사진의 위치를 이 코드가 복원하거나 이미지 내용으로 추정하지는 않습니다. 아래 예제는 Python 3.12.14·Pillow 12.3.0에서 실행했습니다. 재현용 JPEG에 지정한 좌표를 기록한 뒤 다시 읽으며, 실제 여행 사진이나 촬영 이력을 사용하지 않습니다.
설치와 실행
python -m pip install Pillow==12.3.0
python photo_gps.py아래 코드를 photo_gps.py로 저장합니다. 지도 링크를 생성하는 부분에는 Google Maps API 키가 필요하지 않습니다. 글 아래의 웹페이지 내 지도 표시 방식은 별도의 API 설정을 사용합니다.
from io import BytesIO
from PIL import Image
from PIL.TiffImagePlugin import IFDRational
def decimal_degrees(values, ref):
# Pillow의 IFDRational과 숫자 값을 모두 float으로 변환합니다.
degrees, minutes, seconds = map(float, values)
value = degrees + minutes / 60 + seconds / 3600
return -value if ref in ('S', 'W') else value
def read_location(source):
with Image.open(source) as image:
gps = image.getexif().get_ifd(34853)
if not all(key in gps for key in (1, 2, 3, 4)):
return None
return decimal_degrees(gps[2], gps[1]), decimal_degrees(gps[4], gps[3])
# 재현용 JPEG에 예제 좌표를 기록합니다. 실제 촬영 사진이 아닙니다.
exif = Image.Exif()
exif[34853] = {
1: 'N', 2: (IFDRational(37), IFDRational(34), IFDRational(30)),
3: 'E', 4: (IFDRational(126), IFDRational(58), IFDRational(36)),
}
with_gps = BytesIO()
Image.new('RGB', (1, 1)).save(with_gps, format='JPEG', exif=exif)
with_gps.seek(0)
latitude, longitude = read_location(with_gps)
print(f'좌표: {latitude:.6f}, {longitude:.6f}')
print(f'https://www.google.com/maps/search/?api=1&query={latitude:.6f},{longitude:.6f}')
# GPS 정보가 없는 JPEG도 같은 함수로 처리합니다.
without_gps = BytesIO()
Image.new('RGB', (1, 1)).save(without_gps, format='JPEG')
without_gps.seek(0)
print('GPS 없음:', read_location(without_gps))
print('남반구:', decimal_degrees((33, 52, 0), 'S'))
실행 결과
좌표: 37.575000, 126.976667
https://www.google.com/maps/search/?api=1&query=37.575000,126.976667
GPS 없음: None
남반구: -33.86666666666667
내 사진에 적용하기
location = read_location("my_photo.jpg")
if location is None:
print("사진에 GPS 정보가 없습니다.")
else:
latitude, longitude = location
print(f"{latitude:.6f}, {longitude:.6f}")예제의 도·분·초 좌표는 십진수 37.575000, 126.976667로 변환됩니다. GPS가 없는 파일은 None을 반환하고, 남위·서경은 음수로 표시합니다. 위도나 경도가 0이어도 유효한 값이므로, Flask 예제에서도 is not None으로 검사합니다.
사진을 메신저로 전달하거나 다시 저장하는 과정에서 EXIF가 제거될 수 있습니다. 원본 파일에 GPS가 없는 경우에는 촬영 당시의 위치 기록 등 별도 정보가 필요합니다.
EXIF 데이터란 무엇인가요?
EXIF(Exchangeable Image File Format)는 디지털 사진 파일에 포함된 메타데이터로, 촬영 날짜, 시간, 카메라 설정, GPS 위치 정보 등 다양한 정보를 담고 있습니다. 특히 GPS 정보는 사진이 촬영된 정확한 위치를 알려주어 여행 경로를 재구성하는 데 큰 도움이 됩니다.

내가 사진을 촬영했던 장소는 어디였을까?
먼저, google maps api key 를 이용하여, google map 에 위치를 띄워보는 연습부터 해볼수 있습니다!
여기선 vscode 를 사용하여 개발했습니다.
1. 필수 라이브러리 설치
pip install flask pillow

2. Flask 서버 코드 작성
app.py 파일명으로 다음 코드를 작성 합니다.
import os
from flask import Flask, render_template, request, redirect, flash
from PIL import Image, ExifTags
app = Flask(__name__)
app.secret_key = 'your_secret_key'
UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def get_exif_data(image):
"""이미지에서 EXIF 데이터를 추출하고, GPS 정보를 분리하여 반환"""
exif_data = {}
info = image._getexif()
if info is None:
return exif_data
for tag, value in info.items():
decoded = ExifTags.TAGS.get(tag, tag)
if decoded == "GPSInfo":
gps_data = {}
for t in value:
sub_decoded = ExifTags.GPSTAGS.get(t, t)
gps_data[sub_decoded] = value[t]
exif_data[decoded] = gps_data
else:
exif_data[decoded] = value
return exif_data
def get_decimal_from_dms(dms, ref):
"""GPS 좌표(DMS)를 십진수로 변환"""
degrees = float(dms[0])
minutes = float(dms[1])
seconds = float(dms[2])
decimal = degrees + minutes / 60 + seconds / 3600
if ref in ['S', 'W']:
decimal = -decimal
return decimal
def get_lat_lon(exif_data):
"""EXIF 데이터에서 위도와 경도를 추출"""
lat = None
lon = None
if "GPSInfo" in exif_data:
gps_info = exif_data["GPSInfo"]
if ("GPSLatitude" in gps_info and "GPSLatitudeRef" in gps_info and
"GPSLongitude" in gps_info and "GPSLongitudeRef" in gps_info):
lat = get_decimal_from_dms(gps_info["GPSLatitude"], gps_info["GPSLatitudeRef"])
lon = get_decimal_from_dms(gps_info["GPSLongitude"], gps_info["GPSLongitudeRef"])
return lat, lon
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if 'photo' not in request.files:
flash('파일이 없습니다')
return redirect(request.url)
file = request.files['photo']
if file.filename == '':
flash('선택된 파일이 없습니다')
return redirect(request.url)
if file:
filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(filepath)
image = Image.open(filepath)
exif_data = get_exif_data(image)
lat, lon = get_lat_lon(exif_data)
if lat is not None and lon is not None:
# 추출한 좌표와 파일명을 map.html 템플릿으로 전달
return render_template('map.html', lat=lat, lon=lon, filename=file.filename)
else:
flash('GPS 정보가 없는 이미지입니다')
return redirect(request.url)
return render_template('upload.html')
if __name__ == '__main__':
app.run(debug=True)
3. HTML 템플릿 구성

Flask 템플릿 디렉터리(templates)에 두 개의 HTML 파일을 생성합니다.
3.1. 이미지 업로드 페이지 (templates/upload.html)
이미지를 업로드할 수 있는 간단한 폼을 구성합니다.
<pre>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>이미지 업로드</title>
</head>
<body>
<h1>이미지 업로드</h1>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form method="post" enctype="multipart/form-data">
<input type="file" name="photo" accept="image/*">
<input type="submit" value="업로드">
</form>
</body>
</html>
</pre>
4.2. 구글지도 표시 페이지 (templates/map.html)
<pre>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>구글지도에 위치 표시</title>
<style>
#map {
height: 500px;
width: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY"></script>
<script>
function initMap() {
var location = {lat: {{ lat }}, lng: {{ lon }}};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: location
});
var marker = new google.maps.Marker({
position: location,
map: map,
title: '사진 촬영 위치'
});
}
</script>
</head>
<body onload="initMap()">
<h1>사진 촬영 위치</h1>
<div id="map"></div>
<p>업로드한 파일: {{ filename }}</p>
</body>
</html>
</pre>
업로드된 이미지에서 추출한 GPS 좌표를 활용해 구글 지도에 마커를 표시합니다. 반드시 아래 코드에서 YOUR_GOOGLE_MAPS_API_KEY 부분을 본인의 구글 API 키로 변경하세요.
5. 실행하기
1. app.py (오른쪽 상단 실행 버튼 을 누르고 서버 화면을 띄웁니다)

2.http://127.0.0.1:5000/ 주소로 접속 후 이미지를 업로드 하면 google map 화면에 다음과 같이 촬영 장소가 표시 됩니다.

3. 촬영 장소 를 상세히 확인을 할 수가 있습니다.

촬영한 장소를 파이썬 프로그램을 통해 간단히 지도에 표시하는 기능을 테스트 했습니다.
이제 다음 단계로, 해당 위치 주변의 맛집과 관광지 정보를 함께 표시하는 기능을 추가해보겠습니다. 사진의 EXIF 정보를 통해 주변의 흥미로운 장소들을 발견하여 새로운 여행 계획까지 가능 하구요!